Search code examples
ruby-on-railsruby-on-rails-4delayed-job

Delayed Job - Rails 4


I have installed delayed job (gem 'delayed_job_active_record'), but I do not understand a couple of things about its functionality.

First of all after installing delayed_job, I would expect all my delay() methods to work out of the box, and not having to manually start delayed_job.

Now in the README it says that

script/delayed_job can be used to manage a background process which will start working off jobs.

After a few lines it mentions,

If you want to just run all available jobs and exit you can use rake jobs:work

What is the difference between those 2 and which one should I use in my production sever?

If I use rake jobs:work should I start a new thread in a initializer?

Thread.new do
   system(rake jobs:work)
end

Is that a good practice?


Solution

  • Use script/delayed_job for production - your capistrano deployment would call the following after pushing new code

    RAILS_ENV=production script/delayed_job stop
    RAILS_ENV=production script/delayed_job start
    

    NOTE

    Rails 4: replace script/delayed_job with bin/delayed_job

    Usually in development I will execute jobs 'in-process', but optionally specify an environment var to run when I want to simulate production

    see https://github.com/collectiveidea/delayed_job#gory-details - config/initializers/delayed_job_config.rb

    # execute job synch during tests and dev
    # or pass arg for async in those environments
    delayed_execution = if ENV['DELAY_JOBS']
      true
    else
      !(Rails.env.test? or Rails.env.development?)
    end
    
    Delayed::Worker.delay_jobs = delayed_execution
    

    then if you want to run in dev with the delay in separate process boot up both rails and the job process - NOTE that delayed job does NOT auto load changes, you have to restart it each time

    $ DELAY_JOBS=true rails s 
    $ DELAY_JOBS=true bundle exec rake jobs:work