如何在多线程Unicorn Sinatra服务器中仅在一个线程中运行函数?

问题描述 投票:0回答:1

我将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中,但我不确定这是否是放置此代码的最佳位置。

sinatra unicorn
1个回答
1
投票
但是,您可以通过将派生后的工作程序编号保存到环境变量中,然后在应用程序代码中检查其值来解决此问题。

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
© www.soinside.com 2019 - 2024. All rights reserved.