sidekiq的定时任凭之Sidekiq-Cron
之前介绍过sidekiq定时任务用whenever,使用中发现莫名的消耗内存,于是又找其它的gem试试,发现Sidekiq-Cron还不错。其它类似包:minicron、resque-scheduler、rufus-scheduler、Clockwork、sidekiq-scheduler
一、安装
gem install sidekiq-cron
或者在Gemfile里添加
gem "sidekiq-cron" # bundle install
二、使用
如果在ruby而不是在rails中使用,需要在require 'sidekiq' 后加上require 'sidekiq-cron'
Sidekiq::Cron::Job.create(name: 'Hard worker - every 5min', cron: '*/5 * * * *', class: 'HardWorker') # execute at every 5 minutes, ex: 12:05, 12:10, 12:15...etc
# => true # return only true/false
也可以分开写:
job = Sidekiq::Cron::Job.new(name: 'Hard worker - every 5min', cron: '*/5 * * * *', class: 'HardWorker')
if job.valid?
job.save
else
puts job.errors
end
#or simple
unless job.save
puts job.errors #will return array of errors
end
加载多个任务,如果为空会删除任务,如果名称相同会修改,如果不存在会新增
hash方式:
hash = {
'name_of_job' => {
'class' => 'MyClass',
'cron' => '1 * * * *',
'args' => '(OPTIONAL) [Array or Hash]'
},
'My super iber cool job' => {
'class' => 'SecondClass',
'cron' => '*/5 * * * *'
}
}
Sidekiq::Cron::Job.load_from_hash hash
数组方式:
array = [{
'name' => 'name_of_job',
'class' => 'MyClass',
'cron' => '1 * * * *',
'args' => '(OPTIONAL) [Array or Hash]'
},
{
'name' => 'Cool Job for Second Class',
'class' => 'SecondClass',
'cron' => '*/5 * * * *'
}
]
Sidekiq::Cron::Job.load_from_array array
load_from_hash的方式也可以把任务信息写入yml文件里,使用YAML.load_file加载后使用。
三、Web展示
路由里加入require 'sidekiq/cron/web',放在require 'sidekiq/web'后面,将会在栏目的最后加上cron栏目。
四、其它
查找任务:
#return array of all jobs
Sidekiq::Cron::Job.all
#return one job by its unique name - case sensitive
Sidekiq::Cron::Job.find "Job Name"
#return one job by its unique name - you can use hash with 'name' key
Sidekiq::Cron::Job.find name: "Job Name"
#if job can't be found nil is returned
删除任务:
#destroys all jobs
Sidekiq::Cron::Job.destroy_all!
#destroy job by its name
Sidekiq::Cron::Job.destroy "Job Name"
#destroy found job
Sidekiq::Cron::Job.find('Job name').destroy
其它处理:
job = Sidekiq::Cron::Job.find('Job name')
#disable cron scheduling
job.disable!
#enable cron scheduling
job.enable!
#get status of job:
job.status
# => enabled/disabled
#enqueue job right now!
job.enque!