我有一個簡單的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
任何想法?我也很樂意知道另一種緩存計算的更好方法,以及如何每分鐘更新一次。
嗯。我現在看着[delayed_job](http://rubygems.org/gems/delayed_job),正如SO提出的[question](http://stackoverflow.com/questions/3268832/is-it-a-壞主意到創建工作者線程-IN-A-服務器進程)。 – Dan