Last Updated: February 25, 2016
·
1.42K
· macfanatic

Timed Interval Event Loop in Ruby

I recently had the need to write some code that pinged a web service at a regular interval (had to be very precise due to rate limiting) and do a defined action with the result.

In order to write that, I first put it all in a class, MyService. But then I had to find a way to repeat that functionality every 5 seconds. At first I tried Delayed::Job, but it's not very precise and was going to eat up the database tables with records over time as I continuously injected new rows. There wasn't anything dynamic in nature, so it made sense to use another technology.

Instead I choose to write a daemon using the daemons gem, and then use the rev library to write an event loop.

Full code available: https://gist.github.com/4276211

This allows me to start the service from the command line and ensure that it is running every 5 seconds.

$< cd rails_root RAILS_ENV=production script/scheduler restart

You can easily craft a capistrano recipe to do this for you on restart/start/stop of your server, very much how you're told to integrate Delayed::Job into your recipes.