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!
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With