views:

221

answers:

4

I am attempting to create a web-based game in Ruby on Rails. I have a model named 'Game', which has a datetime in the database entry that corresponds to a time that I would like the server to call the Game model's update_game function. Depending on the game's settings, this could be every 30 seconds to every 12 hours.

Ruby on Rails only seems to work when it receives an HTTP request; is there a slick way to get my game to update on a periodic basis independent of HTTP requests?

+1  A: 

Look into background processing options and possibly cron.

srboisvert
+1  A: 

Rails itself doesn't do this; cron does this. Ruby does, however, have a gem named Whenever to make easier the declaration and deployment of new cron jobs.

However, if you are really going to expect a large amount of games to reliably update every 30 seconds, you may want to take a different approach if updating a game would take any significant amount of time. Perhaps once the game is accessed, the game could run the update as many times as necessary (e.g. if 3 minutes had passed and the interval is 30 seconds, run 6 updates once requested). This may or may not be a good option for your setup, however, so figure out which method is more viable for your purposes.

Matchu
The difficulty with updating whenever the game is accessed, is the fact that the game will be updating child objects, and grandchildren objects. I would have to put similar code in every descendent of the game, and it seems like it would be easy to introduce bugs if I add a grandchild, but forget to put in the before_filter to update the game when it gets accessed.
Ryan
So it's more than one controller? Then I suppose cron definitely stands as the better solution. Whenever is a great tool :)
Matchu
If you're worried about forgetting a "before_filter", then why don't you create a class which inherits from ActionController, with all the settings and methods it needs, and then have all your controllers inherit from that?
Trevoke
A: 

I like the gem 'rufus-scheduler' which works within Rails, though I'm not sure you can programmatically add more tasks to it.

Trevoke
+1  A: 

I'd look into delayed_job for this. When the game starts, you can create a delayed_job for the first update, and every run after that can add a new job at the correct interval until it's done.

I'd do lots of testing though ;) - you don't want to let the jobs get away from you.

dunedain289