Rails execute script as background job

空扰寡人 提交于 2019-12-06 07:04:27

Calling the self.delay method from your controller won't work, because DJ will try to serialize your controller into the Job. You'd better create a class to handle your task then flag its method as asynchronous :

class AsyncTask
  def run
    system('ruby my_script.rb')
  end
  handle_asynchronously :run
end

In your controller :

def create
    ...
    AsyncTask.new.run
    ...
end

See the second example in the "Queing Jobs" section of the readme.

Like Jef stated the best solution is to create a custom job. The problem with Jef's answer is that its syntax (as far as I know) is not correct and that's his job handles a single system command while the following will allow you more customization:

# lib/system_command_job.rb
class SystemCommandJob < Struct.new(:cmd)
  def perform
    system(cmd)
  end
end

Note the cmd argument for the Struct initializer. It allows you to pass arguments to your job so the code would look like:

Delayed::Job.enqueue(SystemCommandJob.new("ruby my_script.rb"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!