Arthur Chang

Entrepreneur, Software Engineer, and Photographer
« Back to blog
Nov 17
Views

Run cron jobs or any process easily with delayed_job

last one

 

The delayed_job gem has been around for a little while.  It's a great way to run cron jobs as well as any other background running process.  Some people think it can only be spawned once in awhile, triggered by some other action, but it's a lot more flexible.

At Fanvibe, I've built a huge array of delayed_job workers that are helping us with jobs such as fetching new sport stats every half second, then crunching all that data and figuring out who needs to see that data, as well as grabbing cool heuristics to help us create awesome polls with a mashup of user activity, player and team stats, time, and more.  This is all getting crunched in the background with delayed_job.

The trick is quick re-queueing of the job in an ensure block.  Unlike a message broker system (like rabbitMQ), this stores jobs in the database as one row with a marshalled string to hold things like parameters.  The read/writes are fast enough for things other than chat messaging and real-time collaborative stuff (i'm talking about actual real time within 20ms).

It also has total access to the rails environment, so you can do things like access ActiveRecord etc.

Below is a quick gist of how you would run the delayed_job worker:

Also know, you'll have to kick it off manually the first time.  Just go into your console and do the Delayed::Job.enqueue

 

(photo taken in San Diego a little while ago)