【问题标题】:How do I run a function in only one thread in a multi-threaded Unicorn Sinatra server?如何在多线程 Unicorn Sinatra 服务器中仅在一个线程中运行函数?
【发布时间】:2019-10-23 18:29:25
【问题描述】:

我将我的 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 分钟运行七次,pulled the repo!!! 被打印七次。

有没有办法只在一个线程中运行这个任务?我尝试将其放在worker_processes 7 行上方的 unicorn.rb 中,但我不确定这是否是此代码所在的最佳位置。

【问题讨论】:

    标签: sinatra unicorn


    【解决方案1】:

    Unicorn 是一个多进程(非多线程)机架服务器。仅在其中一个工作进程中执行特定代码路径没有本机支持。

    但是,您可以通过将 fork 后的工作人员编号保存到环境变量中,然后在应用程序代码中检查其值来解决此问题。

    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
    

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多