Search code examples
ruby-on-railsrubyruby-on-rails-3initializationdelayed-job

Initialize the Delayed Jobs gem by starting the workers on application start


I am using Ruby on Rails 3.0.9 and I am trying to setup the delay_job gem. All works if, after rebooting the Apache2 server, I run in the Terminal\Console following commands:

RAILS_ENV=development script/delayed_job stop
RAILS_ENV=development script/delayed_job -n 2 start

However, since I always want to start the workers on application start, in my config/initializers/delayed_job.rb I add the following code (that handles both development and production mode):

if Rails.env.development?
  system 'RAILS_ENV=development script/delayed_job stop'
  system 'RAILS_ENV=development script/delayed_job -n 2 start'
elsif Rails.env.production?
  system 'RAILS_ENV=production script/delayed_job stop'
  system 'RAILS_ENV=production script/delayed_job -n 2 start'
end

However, by using the above code and after re-rebooting the Apache2 server, the DJ gem doesn't work anymore as expected. That is, it doesn't process jobs as it makes when I run the above command lines in the Terminal\Console.

How can I make DJ to work correctly? What is the problem?

P.S.: I would like to do that in order to automatize processes.


It seams that the above code in the config/initializers/delayed_job.rb file doesn't "create" the "pids" files related to DJ in the RAILS_ROOT/tmp/pids directory. Those are created only by running the above command lines manually. Why this happens?


UPDATE for @Devin M

My config/initializers/delayed_job.rb contains:

# Options
Delayed::Worker.destroy_failed_jobs = false
Delayed::Worker.sleep_delay = 2
Delayed::Worker.max_attempts = 5
Delayed::Worker.max_run_time = 1.hour
Delayed::Worker.delay_jobs = !Rails.env.test?

if Rails.env.development?
  system "RAILS_ENV=development #{Rails.root.join('script','delayed_job')} stop"
  system "RAILS_ENV=development #{Rails.root.join('script','delayed_job')} -n 2 start"
elsif Rails.env.production?
  system "RAILS_ENV=production #{Rails.root.join('script','delayed_job')} stop"
  system "RAILS_ENV=production #{Rails.root.join('script','delayed_job')} -n 2 start"
end

Solution

  • Try using this code:

    system "RAILS_ENV=production #{Rails.root.join('script','delayed_job')} stop"
    system "RAILS_ENV=production #{Rails.root.join('script','delayed_job')} -n 2 start"
    

    Testing it in the console produced this output which indicates it should work:

    Loading development environment (Rails 3.0.9)
    ruby-1.9.2-p290 :001 > Rails.root.join('script','delayed_job')
     => #<Pathname:/home/devin/testsoapp/script/delayed_job> 
    ruby-1.9.2-p290 :002 > "RAILS_ENV=production #{Rails.root.join('script','delayed_job')} -n 2 start"
     => "RAILS_ENV=production /home/devin/testsoapp/script/delayed_job -n 2 start" 
    ruby-1.9.2-p290 :003 >