THE DEFINITIVE GUIDE
How to create scheduled jobs in rails using the sidekiq-cron gem
First of all, we need to understand what a scheduled job is. Scheduled jobs are those which are written to run periodically at specific times or dates or certain intervals. They are also known as cron jobs. According to Wikipedia, a cron is a time-based job scheduler in Unix-like computer operating systems.
Now we know what a scheduled job or a cron job is. Lets move on to sidekiq-cron. It is a scheduling add-on for sidekiq. This is not an official sidekiq gem. Scheduling in sidekiq is an enterprise level feature. If you don’t want to spend on that, this gem is for you.
So, lets dive in.
First we need to add the gem to the
Gemfile of your rails app.
run bundle install every time you add a new gem.
Then create a file called
schedule.yml under the config directory. Inside that file, add the following:
Here it says 5. It means it will perform the work in every 5 minute intervals. You also have to change the class called WorkerName to something meaningful for your context.
Now create another file called
config/initializers of your app. Add the following code to that file:
Now its time for you to create the actual worker. For that go to the terminal and type
rails g sidekiq:worker WorkerName
This will create a
workers/worker_name.rb in the app directory of the application. Note that here I am using WorkerName as the name of the worker. If you have modified it earlier, then you need to change it now also. Open it and add some code that will run periodically. Like for example it can be a call to a specific endpoint to check whether there are any new values available and if there is, then save it to the database. ( Don’t worry, it’s just an example)
worker_name.rb file will be like the following:
One last thing. Take the terminal and type
This will run the worker in one tab in the terminal. Make sure to move to another tab if you want to run rails server or anything else. Because the worker needs to run all the time while the app is running.
That’s it. You have created your first sidekiq-cron job. Woohoo!!