Django / Python - update database every second

I am working on building a browser game in Django and Python and I am trying to find a solution to one of the problems I have.

Essentially, several user variables need to be updated every second. For example, there is a currency variable that has to increase by some amount every second, gradually increasing as all this jazz grows.

It seems to me that it is a bad idea to do it with cronjobs (and from my research, other people think so too), so right now I think that I should just create a thread that will go through all users in the database that does these updates.

Am I on the right track here, or is there a better solution? In Django, how can I start a thread, the second of which starts the server?

I appreciate your understanding.

+3


source to share


2 answers


One possible solution would be to use a separate daemonized lightweight python script to execute all the business logic in the game, and the left django would just be the interface to your game. To chain them together, you can choose any high performance asynchronous messaging library like ZeroMQ (for example, to pipe player actions to this script). This stack will also have the advantage of an interface that will be split and completely incompatible with the backend implementation.



+2


source


Generally, the best solution would be not to update every currency every second. Instead, save the timestamp of the user's last transaction, rate of income, and their last balance . With these three pieces of data, you can calculate their current balance when needed.

When a user makes a purchase, for example, it performs math to calculate what its new balance is. Some pseudocode:



def current_balance(user):
    return user.latest_balance + user.income * (now() - user.last_timestamp)

def purchase(user, price):
    if price > current_balance(user):
        print("You don't have enough cash.")
        return

    user.balance = current_balance(user) - price
    user.last_timestamp = now()
    user.save()
    print("You just bought a thing!")

      

In such a system, your database will only be updated with user interaction, which will make your system scale better.

+1


source







All Articles