0

Previously for my PHP app, I used a cron job that increments the health of a user in SQL every 10 minutes and the cron job script incremented the health of all users.

For my next app, I tried using MySQL events to increment the health every minutes for each individual user and ran into some problems with them not working after awhile (MySQL events stop working after awhile)

What's the best way to do this if I were to create a new app in Ruby on Rails? I'm open to using MySQL or PostgreSQL.

This is for a game where users will fight each other and lose health.

edit: Sometimes the user will encounter another user, and I need to select that user based on their health among other things. So I need the actual health stored in the database.

Community
  • 1
  • 1
Andy
  • 1,815
  • 2
  • 22
  • 49
  • 3
    I'd avoid doing it at all if I could. Could you solve your problem by storing when a health value was saved and adjusting it up whenever it's retrieved by the number of minutes that have passed? – Dan Nov 21 '13 at 20:41

3 Answers3

3

Instead updating every record in the database every 10 minutes, store a last-modified timestamp in the same row as the health. Every time you read the player_health from the database, add (current_time - last_modified) / (10 min) to the value. Every time you write player_health to the database, update the last_modified.

Anon
  • 10,660
  • 1
  • 29
  • 31
0

I would create a rake task that increases all users' health by 10, and call it using the awesome whenever gem every 10 minutes.

UPDATE

However, as Dan said in his comment, it might be inefficient to do such a huge DB update every 10 seconds (especially if you have huge number of users) if you can just update every user's health when he requests that. But that's subject to how your game actually works.

Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82
  • 1
    Just to make clear: whenever is a Ruby DSL for cron, so if you use whenever you are choosing the cron path. – zwippie Nov 21 '13 at 20:55
  • @zwippie I think his problem isn't that he doesn't want to use cronjobs, but that he doesn't know how to actually make them work with rails. – Tamer Shlash Nov 21 '13 at 21:00
  • 1
    That is possible, my comment only added that whenever uses cron, not that he should avoid cron or anything. – zwippie Nov 21 '13 at 21:05
0

The correct fix, given a health bump of 10 points every minute, is a hitpoints variable and a timestamp for the last time it was set. Then the select statement will say "hitpoints + minutes(now - timestamp) * 10". Converting that to SQL is left as an exercise for the reader.

Phlip
  • 5,253
  • 5
  • 32
  • 48