安装
gem install sidekiq
gem install sidekiq-cron
新建job
class FirstJob < ApplicationJob
queue_as :default
def perform
Article.create!(title: 'first', text: 'this is a demo')
end
end
这里写的定时任务基于active job,其余的写法请查看sidekiq-cron
/config中新建schedule.yml
FirstJob:
cron: "0 0 0 20 * *"
class: FirstJob
上面代码的意思是每个月20号执行定时任务firstjob,关于更多cron的用法,请查看Cron Format
/config/initializers中新建sidekiq.rb
schedule_file = 'config/scheduler.yml'
if File.exist?(schedule_file) && Sidekiq.server?
Sidekiq::Cron::Job.load_from_hash YAML.load_file(schedule_file)
end
配置
/config/application.rb文件中添加:
config.active_job.queue_adapter = :sidekiq
启动
redis-server & sidekiq
由于redis为sidekiq提供数据存储,所以启动sidekiq前必须先启动redis,更多请查看redis