Sidekiq - Deleting scheduled jobs when task is deleted

I schedule reminder emails when a user creates a task for a certain date using the following code in the create action:

if @post.save
  EmailWorker.perform_in(@time.minutes, @post.id)
end

I want to delete the scheduled reminder mail whenever the associated task is deleted. I tried using a model method on before_destroy:

before_destroy :destroy_sidekiq_job

def destroy_sidekiq_job
  post_id = self.id
  queue = Sidekiq::Queue.new('critical')
  queue.each do |job|
    if job.klass == 'EmailWorker' && job.args.first == post_id
      job.delete
    end
  end
end

However, the jobs aren't deleted from the queue. Any suggestions for me to fix this?

Answers


The scheduled jobs are not within a queue yet, use Sidekiq::ScheduledSet to find the scheduled jobs:

def destroy_sidekiq_jobs
  scheduled = Sidekiq::ScheduledSet.new
  scheduled.each do |job|
    if job.klass == 'EmailWorker' && job.args.first == id
      job.delete
    end
  end
end

Don't do this. Let Sidekiq execute the job but verify the post exists and is current when the email job is run.

def perform(post_id)
  post = Post.find_by_id(post_id)
  return unless post

  ...
end

Need Your Help

Java Using Robot to Output letters (Capitalized and uncapitalized)

java methods awtrobot

I am using this method to try and type out my letters into a form. Though when the char gets converted back to chars, they are not capitalized. What would be the most efficient way to capitalize sp...

picture viewer in c# .net

c# image-processing

Regarding .Net technology,What will be the basic element of a picture viewer(like Windows Picture and Fax Viewer)? Is it a user control inside a form, or is it something other components. Could you

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.