Rails 5 — Configuring Sidekiq to use cron scheduler
If you are not familiar with sidekiq usage go through this blog post first.
A cron job is time-based job scheduler in Unix-like computer operating systems (src: Wikipedia). Setting up a cron tab is pretty easy but you can take advantage of your running rails application for doing so.
Sidekiq can also be used to run cron jobs. This can be done with sidekiq-scheduler gem.
gem install sidekiq-scheduler
Let’s start with creating a job which would run as a scheduled cron job
# app/jobs/demo_job.rb# frozen_string_literal: trueclass DemoJob < ApplicationJob
def perform
puts 'I run at 8 everyday'
end
end
Add the following to configuration file from previous blog
# config/sidekiq.yml---
:verbose: false
:concurrency: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
:timeout: 30:queues:
- [low_priority, 1]
- [high_priority, 2] # high priority:schedule:
DemoJob:
cron: '0 8 * * *'
queue: scheduler
enabled: true
This tell sidekiq handlers to create a cron schedule running at 8 everyday. The job will be queued to scheduler
queue.
That’s it, now you can forget about setting up a cron tab.
Useful commands
- Get all schedules
Sidekiq.get_schedule# this returns =>
{"DemoJob"=>{"cron"=>"0 8 * * *", "queue"=>"scheduler", "enabled"=>true, "class"=>"DemoJob"}}
2. Set dynamic schedule
Schedule changes are loaded every 5 seconds. To allow dynamic schedule add dynamic: true
in the sidekiq configuration file.
# This will run demo job every minSidekiq.set_schedule('DemoJob', { 'every' => ['1m'], 'class' => 'DemoJob' })
3. To see the scheduler jobs in the sidekiq dashboard. Add this to your routes.rb
require 'sidekiq/web'
require 'sidekiq-scheduler/web'mount Sidekiq::Web => '/sidekiq'
Go to /sidekiq

4. You can use cron tab guru to verify cron schedule.
That’s all you need to know to set up a cron scheduler. To know more about the options available you can check the official git repo.