Delayed_job. Remove job from queue

class Radar include Mongoid::Document after_save :post_on_facebook private def post_on_facebook if self.user.settings.post_facebook Delayed::Job.enqueue(::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from) end end end class FacebookJob < Struct.new(:user,:body,:url,:title) include SocialPluginsHelper def perform facebook_client(user).publish_feed('', :message => body, :link => url, :name => title) end end 

I want to execute the post_on_facebook method on a specific date. I store this date in the field "active_from".

The code above works, and the task runs on the correct date.

But in some cases, I first create a Radar object and send some job to the Delayed Job queue. After that, I update this object and submit another job to the Delayed Job.

This is a misbehavior because I will not complete the task only once at the right time. In this implementation, I will have 2 tasks to be completed. How can I delete a previous task so that only the updated one will be completed?

 Rails 3.0.7 Delayed Job => 2.1.4 https://github.com/collectiveidea/delayed_job 

ps: sorry for my english, I try to do my best

+7
source share
2 answers

It looks like you want to disable any tasks if the radar object is updated and reordered.

Delayed :: Job.enqueue should return the Delayed :: Job entry so that you can remove the identifier and save it in the Radar record (create a field for it on the radar document) so that you can find it again later easily.

You must change it to before_save so as not to introduce an infinite save loop.

 before_save :post_on_facebook def post_on_facebook if self.user.settings.post_facebook && self.valid? # delete existing delayed_job if present Delayed::Job.find(self.delayed_job_id).destroy if self.delayed_job_id # enqueue job dj = Delayed::Job.enqueue( ::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from ) # save id of delayed job on radar record self.delayed_job_id = dj.id end end 
+13
source

You tried to save the identifier from the pending job, and then save it for possible deletion: for example

 job_id = Delayed::Job.enqueue(::FacebookJob.new(self.user,self.body,url,self.title),0,self.active_from) job = Delayed::Job.find(job_id) job.delete 
+3
source

All Articles