我将cron任务放在一个模块中,然后放在我的Sinatra服务器中。
module Cron
scheduler = Rufus::Scheduler.new
scheduler.every "30m", :first => :now do
run_cmd('git pull')
puts "pulled the repo!!!"
end
end
class MyServer < Sinatra::Base
include Cron
end
应用程序的入口点是独角兽(unicorn config/config.ru -p 9393 -c config/unicorn.rb
),在unicorn.rb
中有此行
worker_processes 7
因此,git pull每30分钟运行7次,并且pulled the repo!!!
被打印7次。
是否有一种方法可以仅在一个线程中运行此任务?我尝试将其放在worker_processes 7
行上方的unicorn.rb中,但我不确定这是否是放置此代码的最佳位置。
在config/unicorn.rb
中使用
after_worker_ready do |server, worker|
ENV["WORKER_NR"] = worker.nr.to_s
end
在您的Sinatra应用程序中执行:
if unicorn_worker_nr == "0"
scheduler.every "30m", :first => :now do
...
end
end
def unicorn_worker_nr
ENV["WORKER_NR"]
end