简体   繁体   中英

Rails execute script as background job

I've a ruby script that has been implemented as an independent functionality. Now I would like to execute this script in my rails environament, with the added difficulty of executing it as a background job, because it needs a great amount of time processing.

After adding the delayed_job gem, I've tryied calling the following sentence:

delay.system("ruby my_script.rb")

And this is the error I get:

Completed 500 Internal Server Error in 95ms
TypeError (can't dump anonymous module: #<Module:0x007f8a9ce14dc0>):
   app/controllers/components_controller.rb:49:in `create'

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM