user3224820
user3224820

Reputation: 211

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?

Upvotes: 1

Views: 1391

Answers (2)

Mike Perham
Mike Perham

Reputation: 22208

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

Upvotes: 6

infused
infused

Reputation: 24337

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

Upvotes: 4

Related Questions