how to get list of arguments to handler in delayed_job rails
Asked Answered
C

2

8

I have a list of all the scheduled jobs which I can get using the command

Delayed::Job.all

Every job has a handler field(string) which contains a '-' separated arguments. I want to find one of the arguments of this string. One way is obviously to split the string and extract the value but this method will fail if there is ever any change in the list of arguments passed.

Below given is the handler string of one of my job objects:

"--- !ruby/object:ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper\njob_data:\n job_class: ActionMailer::DeliveryJob\n job_id: 7ce42882-de24-439a-a52a-5681453f4213\n queue_name: mailers\n arguments:\n - EventNotifications\n - reminder_webinar_event_registration\n - deliver_now\n - [email protected]\n - yesha\n - 89\n locale: :en\n"

I want to know if there is any way, I can send extra arguments to job object while saving it which can be used later instead of searching in the handler string. Or, if not this, can i get a list of arguments of handler rather than parsing the string and using it.

Kindly help!

Crocodile answered 11/10, 2017 at 8:51 Comment(0)
R
13

There is a method instance_object for Delayed::Job instances which returns the deserialized handler

job = Delayed::Job.first

handler = job.payload_object

You can use your handler as needed, such as handler.method

Reyreyes answered 10/5, 2018 at 9:4 Comment(2)
Sorry, but this does not work. undefined method instance_object' ruby-2.2.4/gems/activemodel-4.2.6/lib/active_model/attribute_methods.rb:433:in method_missingCrocodile
Mmm think I meant job.payload_objectReyreyes
C
4

To access the job data:

data = job.payload_object.job_data

To then return the actual job class that was queued, you deserialize the job data:

obj = ActiveJob::Base.deserialize(data)

If your job is a mailer and you want to access the parameters to your mailer, then this is where things get a bit hacky and I'm unsure if there's a better way. The following will return all of the data for the mailer as an array containing the mailer class, method names, and arguments.

mailer_args = obj.instance_variable_get :@serialized_arguments

Finally, you can deserialize all of the mailer arguments with the following which will contain the same data as mailer_args, but with any ActiveRecord objects deserialized (with the form gid://...) to the actual instances passed to the mailer.

ActiveJob::Arguments.deserialize(mailer_args)
Chao answered 27/10, 2021 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.