2011-09-21 87 views
1

我有一個簡單的Sinatra應用程序,通過Phusion Passenger在Apache上運行。Sinatra和Phusion乘客的線程行爲

當應用程序啓動時,我啓動一個Ruby線程,每分鐘執行一次繁重的計算,將結果留在全局變量中(然後在其他位置訪問)。

當使用rackup時,該變量每分鐘更新和刷新一次,但在Passenger下運行時,似乎沒有這樣做。

# Seed the initial license data - on Sinatra starting - and 
# set it on a global variable. 
$license_data = generate_license_data(360) 

# Start up a worker thread that will update the license data 
# every 60 seconds. This thread will run until termination 
# of the parent thread. Only this thread will modify the values 
# of the global variable "license_data". 
worker_thread = Thread.new do 
    while true 
    sleep 60 
    t = Time.now 
    print "Generating license data ..." 
    $license_data = generate_license_data(360) 
    print " OK (#{seconds_to_string(Time.now-t)})\n" 
    end 
end 

# Generate the actual HTML snippet we need for the license entry 
# by accessing the global variable "license_data". 
def generate_license_entry 
    # The license block. 
    @licensechart = {} 
    @licensechart[:values] = $license_data[:values_string] 
    # Generate the table entry. 
    haml :license 
end 

任何想法?我也很樂意知道另一種緩存計算的更好方法,以及如何每分鐘更新一次。

+0

嗯。我現在看着[delayed_job](http://rubygems.org/gems/delayed_job),正如SO提出的[question](http://stackoverflow.com/questions/3268832/is-it-a-壞主意到創建工作者線程-IN-A-服務器進程)。 – Dan

回答

0

我並不十分注意Passenger,但我認爲它產生了幾個服務響應的過程,因此可能無法更新或訪問該變量。保存和訪問數據庫中的數據至少應解決該問題。對於這種情況,我個人會用ResqueResque Scheduler,這是一個用於創建和處理(循環)後臺作業的庫,這是您現在使用線程執行的操作。

而且,乘客聲明具有高度推測性,可能是錯誤的。

問候

托比亞斯

1

根據已配置的乘客怎麼樣,它可能需要在運行(所以你會複製每個進程中的計算工作)多個進程,或無(如它可以關閉一段時間內未處理請求的實例)。

使用另一個系統來運行後臺任務(比如Resque或delayed_job)會更可靠,並且允許您根據您的Web請求需求配置Passenger,而與您的工作線程要求無關。

相關問題