How would you run code once per second on Heroku?
Heroku supports background workers and cron (daily, hourly) but I'm looking for a way to run code once a second.
Le开发者_Go百科t's say I have a game backend on Heroku and want to timeout some player action after some time.
How would you solve for this?
You should try rufus scheduler:
Install the gem
gem install rufus-scheduler
Make sure you include the gem in bundler or however you are including it.
Then you need to create a file called task_scheduler.rb
and stick this in you initializers
directory.
require 'rufus/scheduler'
scheduler = Rufus::Scheduler.start_new
scheduler.every '1s' do
puts "Test!"
#do something here
end
If you have any trouble you can see this blog post:
http://intridea.com/2009/2/13/dead-simple-task-scheduling-in-rails?blog=company
Some Javascript polling might be an alternative to a Heroku worker that runs some code every second. Something that performs an AJAX call after a given period of time.
Running a Heroku worker to run some code every second doesn't seem hugely cost effective or efficient.
Off the top of my head, perhaps:
var codeToRun = function(){
$.ajax({
url: '/test',
success: function(){
alert('Code was run.');
}
)};
}
timer = window.setInterval(codeToRun,1000);
精彩评论