3

I'm working on creating a browser-based game in Django and Python, and I'm trying to come up with a solution to one of the problems I'm having.

Essentially, every second, multiple user variables need to be updated. For example, there's a currency variable that should increase by some amount every second, progressively getting larger as you level-up and all of that jazz.

I feel like it's a bad idea to do this with cronjobs (and from my research, other people think that too), so right now I'm thinking I should just create a thread that loops through all of the users in the database that performs 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 the server starts?

I appreciate the insight.

3
  • 3
    Might want to use an asynchronous task framework, i.e. celery. Commented Apr 18, 2015 at 19:47
  • You are quite correct that cron jobs is the wrong way to do it. Commented Apr 18, 2015 at 21:14
  • @msw What's wrong with using cron jobs? Commented Apr 19, 2015 at 7:47

2 Answers 2

2

One of the possible solutions would be to use separate daemonized lightweight python script to perform all the in-game business logic and left django be just the frontend to your game. To bind them together you might pick any of high-performance asynchronous messaging library like ZeroMQ (for instance to pass player's actions to that script). This stack would also have a benefit of a frontend being separated and completely agnostic of a backend implementation.

Sign up to request clarification or add additional context in comments.

Comments

2

Generally a better solution would be to not update everyone's currency every second. Instead, store the timestamp of the user's most recent transaction, their income rate, and their latest balance. With these three pieces of data, you can calculate their current balance whenever needed.

When the user makes a purchase for example, do the math to calculate what their 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!")

With a system like this, your database will only get updated upon user interaction, which will make your system scale oodles better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.