Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Cancelling a scheduled job in Sidekiq

So I have a Sidekiq worker in my model which looks like this:

class Perk < ActiveRecord::Base

include Sidekiq::Worker
include Sidekiq::Status::Worker

after_save :update_release_time

def update_release_time
  if self.release_time_changed?
    #if scheduled job already exists then cancel and reschedule
    #  Sidekiq::Status.cancel scheduled_job_id
    #  scheduled_job_id = NotifierWorker.perform_at(time.seconds.from_now, .....)
    #elsif scheduled job doesn't exist, then schedule for the first time
    #  scheduled_job_id = NotifierWorker.perform_at(time.seconds.from_now, .....)
    #end
  end
end
end

So basically, my code checks if the release time has changed. If it has, then it has to cancel the previously scheduled job and schedule it at a new time. How do I achieve this i.e what would go in place of my pseudo-code? How do I check if scheduled_job_id exists and then fetch its id?

like image 258
geekchic Avatar asked Jun 12 '14 09:06

geekchic


People also ask

How do I cancel my Sidekiq job?

According to this Sidekiq documentation page to delete a job with a single id you need to iterate the queue and call . delete on it.

How do I remove a queue from Sidekiq?

The "Queues" tab in the Sidekiq Dashboard has a "Delete" button for each queue.

How does Sidekiq scheduler work?

Sidekiq Scheduler is a lightweight job scheduling extension for Sidekiq. It uses Rufus Scheduler under the hood, that is itself an in-memory scheduler. Sidekiq Scheduler extends Sidekiq by starting a Rufus Scheduler thread in the same process, loading and maintaining the schedules for it.

Should I use Activejob Sidekiq?

If you build a web application you should minimize the amount of time spent responding to every user; a fast website means a happy user.


1 Answers

The API documentation has an overview of what you can do but you really need to dive into the source to discover all the capabilities.

You can do this but it won't be efficient. It's a linear scan for find a scheduled job by JID.

require 'sidekiq/api'
Sidekiq::ScheduledSet.new.find_job(jid).try(:delete)

Alternatively your job can look to see if it's still relevant when it runs.

like image 139
Mike Perham Avatar answered Sep 21 '22 04:09

Mike Perham