Create Ruby on Rails scheduler with Sidekiq and Whenever

When developing web applications, I often encounter a need of implementing some background jobs run regularly. With Ruby on Rails, we have many powerful gems helping us write background job, and sidekiq is a good option. How about scheduling the job to run daily in certain time? You can use crontab on server, set scheduler using curl command to call an API. However, it requires you knowledge about system. Thanks towhenever gem which makes our task much easier in Rails.

Dependencies

Sidekiq is simple, efficient background processing which enqueues your jobs in Redis using multiple threads to run as many jobs as it can in the same time.

Thus, in order to make it work, you will initially need to install Redis on your server. Below is short version how to install Redis on Ubuntu server ( You can ignore this part if you installed Redisbefore )

sudo apt-get update 
sudo apt-get install build-essential tcl 
cd /tmp curl -O http://download.redis.io/redis-stable.tar.gz 
tar xzvf redis-stable.tar.gz 
cd redis-stable 
make 
make test 
sudo make install 
sudo mkdir /etc/redis 
sudo cp /tmp/redis-stable/redis.conf /etc/redis 
sudo nano /etc/redis/redis.conf

Then, to continue, you need to update you config file

# /etc/redis/redis.conf 
# ... 
# change this line 
supervised no 
# to this line 
supervised systemd 
# And change this line 
dir . 
# To 
dir /var/lib/redis

After that, create redis systemd unit file

sudo nano /etc/systemd/system/redis.service

With below content

[Unit]
Description=Redis In-Memory Data Store
After=network.target
[Service]
User=redis
Group=redis
ExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf
ExecStop=/usr/local/bin/redis-cli shutdown
Restart=always
[Install]
WantedBy=multi-user.target

What you need is to run some more commands to make it run

sudo adduser --system --group --no-create-home redis
sudo mkdir /var/lib/redis
sudo chown redis:redis /var/lib/redis
sudo chmod 770 /var/lib/redis
# to start redis
sudo systemctl start redis
# to enable redis at start boot
sudo systemctl enable redis

Continue reading Create Ruby on Rails scheduler with Sidekiq and Whenever