之前介紹過sidekiq定時(shí)任務(wù)用whenever,使用中發(fā)現(xiàn)莫名的消耗內(nèi)存破婆,于是又找其它的gem試試劳闹,發(fā)現(xiàn)Sidekiq-Cron還不錯(cuò)。其它類似包: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
? 加載多個(gè)任務(wù)长捧,如果為空會(huì)刪除任務(wù),如果名稱相同會(huì)修改吻贿,如果不存在會(huì)新增
? 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
? 數(shù)組方式:
? 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的方式也可以把任務(wù)信息寫入yml文件里串结,使用YAML.load_file加載后使用。
三舅列、Web展示
? 路由里加入require 'sidekiq/cron/web'肌割,放在require 'sidekiq/web'后面,將會(huì)在欄目的最后加上cron欄目帐要。
四把敞、其它
查找任務(wù):
???????? #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
刪除任務(wù):
???????? #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!