Rails7+Sidekiq排程系統

Andy Kuan's Blog
4 min readMar 18, 2024

--

以下Rails實作版本 7.x.x以上,Ruby3.3.0最新版 適用

Rails很實用的排程系統

安裝 sidekiq gem + sidekiq需搭配 redis-server

這個Gem需要建構一支yml檔案: sidekiq.yml在rails config裡面.

這篇使用的Gem:

gem 'sidekiq'
gem 'sidekiq-scheduler'

下面這個cron例子是指每5分鐘執行一次TestJob, 下面那個DailyTestJob2範例是指每天上午9:00執行, cron是以24小時制, 其他需求設計可參考linux排程系統, 概念都一樣

:schedule:
DailyTestJob:
cron: '*/5 * * * *'
class: TestJob
enabled: true
DailyTestJob2:
cron: '0 9 * * *'
class: TestJob
enabled: true

上面設定好後,排程檔案寫在rails app/jobs裡面:

# frozen_string_literal: true
require 'sidekiq-scheduler'
class DailyTestJob
include Sidekiq::Worker

def perform
# 這裡面寫要做的事情&&邏輯
end

end

關於cron設定時間日期格式,可以參考以下圖片:

執行指令: bundle exec sidekiq -C config/sidekiq.yml

正式環境執行指令: RAILS_ENV=production bundle exec sidekiq &

基本上以上設定就可以用了,但還不完整,以下是說明將排程設定在正式環境的systemd/system裡面:

建立sidekiq.server檔案在/etc/systemd/system/底下,設定軟連結連到 rails config/sidekiq sercer。sidekiq.server檔案名稱可以自定義,如果要多個專案時。

sidekiq.server檔案基本內容:(以下是使用rvm版本)

# /etc/systemd/system/sidekiq.service
[Unit]
Description=sidekiq
After=syslog.target network.target

[Service]
Type=simple
WorkingDirectory=/path/to/your/app

# 如果是用 rbenv:
# ExecStart=/bin/bash -lc 'exec /home/deploy/.rbenv/shims/bundle exec sidekiq -e production'
# 如果是用 rvm ,用而且專案有 .ruby-version 指定版本
ExecStart=/home/deploy/.rvm/bin/rvm in /home/deploy/product_name/current do bundle exec sidekiq -e production

User=andy
Group=andy
UMask=0002

# 限制使用幾個
Environment=MALLOC_ARENA_MAX=2

# 如果掛掉就重啟
RestartSec=1
Restart=on-failure

# log 會記在 /var/log/syslog
StandardOutput=syslog
StandardError=syslog

# 這個服務的id 是 sidekiq
SyslogIdentifier=sidekiq

[Install]
WantedBy=multi-user.target

啟動與重啟:

sudo systemctl daemon-reload 
sudo systemctl enable sidekiq.service
sudo systemctl restart sidekiq.service
sudo systemctl status sidekiq.service

其他指令(有需要可以用):

# 檢查線程
ps aux | grep sidekiq

# 砍掉 number編號
kill {number}

# 軟連結設定方式
ln -s {絕對路徑} ../path/...

--

--