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

后端 未结 3 1387
时光取名叫无心
时光取名叫无心 2021-01-15 19:07

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 command

3条回答
  •  爱一瞬间的悲伤
    2021-01-15 19:30

    I had a problem where the initializing delayed_job process was running though its initializers before creating the pid file (i.e. delayed_job.pid in case of a single worker and delayed_job.0.pid delayed_job.1.pid etc. in case of many workers)

    So I resorted to creating my own lock file as such:

    Delayed::Worker.destroy_failed_jobs = false
    Delayed::Worker.sleep_delay = 2
    Delayed::Worker.max_attempts = 5
    Delayed::Worker.max_run_time = 4.hour
    Delayed::Worker.delay_jobs = !Rails.env.test?
    
    workers = 2
    
    
    if Rails.env.production? || Rails.env.development?
      # Check if the delayed job process is already running
      # Since the process loads the rails env, this file will be called over and over
      # Unless this condition is set.
      pids = Dir.glob(Rails.root.join('tmp','pids','*'))
    
      system "echo \"delayed_jobs INIT check\""
      if pids.select{|pid| pid.start_with?(Rails.root.join('tmp','pids','delayed_job.init').to_s)}.empty?
    
        f = File.open(Rails.root.join('tmp','pids','delayed_job.init'), "w+") 
        f.write(".")
        f.close
        system "echo \"Restatring delayed_jobs...\""
        system "RAILS_ENV=#{Rails.env} #{Rails.root.join('bin','delayed_job')} stop"
        system "RAILS_ENV=#{Rails.env} #{Rails.root.join('bin','delayed_job')} -n #{workers} start"
        system "echo \"delayed_jobs Workers Initiated\""
        File.delete(Rails.root.join('tmp','pids','delayed_job.init')) if File.exist?(Rails.root.join('tmp','pids','delayed_job.init'))
    
      else
        system "echo \"delayed_jobs is running\""
      end
    end
    

    file: config\initializers\delayed_job.rb

    Note: will not work for windows!

提交回复
热议问题