How to use custom delayed_job jobs with ActiveJob?

I am using DelayedJob and I want to upgrade my Rails 4.2 application to use ActiveJob. The problem is that I have a bunch of custom jobs that look like this:

AssetDeleteJob = Struct.new(:user_id, :params) do def perform # code end # more methods n' stuff end 

Then, somewhere in the controller, the job is placed in this syntax:

 @asset_delete_job = AssetDeleteJob.new(current_admin_user.id, params) Delayed::Job.enqueue @asset_delete_job 

I would like to find the equivalent for ActiveJob. The above is mostly straight from DJ documents. Using it to turn on a single call is as simple as calling a method for completing a task, just like with a DJ. But mine are more complex and require DJ Struct syntax and arguments passed to it.

Here is what I have tried so far:

 class AssetDeleteJob < ActiveJob::Base queue_as :default def initialize(user_id, params) @user_id = user_id @params = params end def perform #code end # more methods n' stuff end job = AssetDeleteJob.new(1, {ids: [1,2,3]}) 

Unfortunately, the object instance does not have the #perform_later method, as I expected. It has #enqueue, but I get an odd error:

Failed to register event "enqueue.active_job". NoMethodError: undefined method `any? 'for nil: NilClass

... followed by a stack trace in the array ending in

NoMethodError: undefined `map 'method for nil: NilClass

An odd pair of errors, but I may not have to access #enqueue directly. The above is similar to what ActiveJob is looking for on the nose. What am I missing?

+6
source share
2 answers

I see two problems. First, you defined the initialize method in your custom job class, thereby overwriting the initialize method in the ActiveJob class. This is what causes the exception to be thrown. I'm not sure that you can play with the creation of active jobs. Secondly, you are trying to call the perform_later class perform_later on an instance of this class that Ruby will not allow.

This is easy to fix, just add arguments to the perform method in your own class:

 class AssetDeleteJob < ActiveJob::Base #code def perform(user_id, params) #do a thing end #more code end 

and then run the task by calling something like:

 AssetDeleteJob.perform_later(1, {ids: [1,2,3]}) 
+5
source
 # in jobs/asset_delete_job.rb class AssetDeleteJob < ActiveJob::Base queue_as :default def perform(user_id, params) AssetService.new(user_id, params).delete # for example end end # somewhere in your controllers/assets_controller.rb AssetDeleteJob.perform_later(1, {ids: [1,2,3]}) 
0
source

Source: https://habr.com/ru/post/982765/


All Articles