ruby on rails: delayed_job does not execute function from module
I want to use delayed_job to execute a function from controller. The function is stored in module lib/site_request.rb:
module SiteRequest
def get_data(query)
...
end
handle开发者_如何学运维_asynchronously :get_data
end
query_controller.rb:
class QueryController < ApplicationController
include SiteRequest
def index
@query = Query.find_or_initialize_by_word(params[:query])
if @query.new_record?
@query.save
get_data(@query)
flash[:notice] = "Request for data is sent to server."
end
end
end
I also tried to remove handle_asynchronously
clause from module and use delay.get_data(@query)
, both do not executed silently (without delayed_job code works)
I had trouble trying to use the built-in delay methods myself, too. The pattern I settled on in my own coding was to enqueue DelayedJobs myself, giving them a payload object from which to work. This should work for you too and would seem to make sense even. (This way, you may not even need your SiteRequest
module, for example.)
class MyModuleName < Struct.new(:query)
def perform
# TODO
end
end
Then, instead of calling get_data(query)
after saving, enqueue with:
Delayed::Job.enqueue(MyModuleName.new(query))
I found the same issue. My environment is:
- Ruby 2.1.7
- Rails 4.2.6
- activejob (4.2.6)
- delayed_job (4.1.2)
- delayed_job_active_record (4.1.1) MY solutions: Turn the module into a class. Instantiate a object from the class and apply the method to the instance. It seems that ActiveJob can enqueue only instances. In your case:
Class SiteRequest def initialize end def get_data(query) ... end handle_asynchronously :get_data end
def index
...
q= SiteRequest.new
q.get_data(@query)
flash[:notice] = "Request for data is sent to server."
end
end
精彩评论