venerdì 14 novembre 2014

Quickly add delayed job to your rails app

In some of my rails app I need to have delayed/background jobs as a consequence of a controller's action call

Below quick instructions on how to add delayed jobs to any rails app:

1- add the following to Gemfile

gem 'delayed_job'
gem 'delayed_job_active_record'
gem 'daemons'

2- execute bundle install

3- create the delayed jobs tables
rails generate delayed_job:active_record

4- migrate the DB
rake db:migrate

5- in your rails root create a directory called jobs

6- add the following lines in config/application.rb
config.autoload_paths += %W(#{config.root}/jobs) #autoload delayed_jobs job
Delayed::Worker.destroy_failed_jobs = false
Delayed::Worker.sleep_delay = 60
Delayed::Worker.read_ahead = 5 #default value

7- in the jobs directory creare delayed_task.rb
DelayedTask =, :y) do

def task_worker
        res = self.x + self.y "Task calculating x + y = " + res.to_s

def perform

8- add somewhere in your controller

Delayed::Job.enqueue(,3), {:priority => 0, :run_at => + 10.seconds})
9- start the jobs worker
rake jobs:work
bin/delayed_job start
10- start your raisl app and when your controller method will be called a new delayed job (DelayedTask) will be schedule and execute at the proper time