Still partialy an OpenQuestion. How do I run background jobs in rails? All the doc I've found so far is for response based code e.g. user pushed button, Ruby bootstraps itself -> runs some code -> sends back a page. How can I just plain, run some code and, for example, change the escalation level on a "bug" record from "normal" to "too old" if a record ages too much? Alternately can I write a background job that'll, for example, spit out a nicely formatted text file every night at 2:00 AM? There are several things that might work, depending on your needs. h2. Forking with Ruby Ruby contains a fork method in the Kernel class that starts a background process. Using it in rails has been discussed: * http://one.textdrive.com/pipermail/rails/2005-March/004592.html * http://redhanded.hobix.com/inspect/daemonize.html I just tried this, and it seems to stall the engine (which is good in that it prevents race conditions, but it means forking isn't the right tool for long running tasks). Here's the code I used:
class HalController < ApplicationController
def tick
Process.detach fork {
now = DateTime.now
sleep 30
Race.new { |r|
r.system = System.find_all.first
r.start_date = now.to_s
r.end_date = DateTime.now.to_s
}.save
}
render_text "tock #{DateTime.now}"
end
end
When several users go to hal/tick at once the race-condition test blocks are all consecutive (no overlap) but the GUIs return in sequence (e.g. several minutes later for the last ones).
--[[MarkusQ]]
h2. Threading with Ruby
http://www.rubycentral.com/book/tut_threads.html
It should be noted that Spinning off Thread's via Thread.new { code_block } will not work with apache. It will however work with lighttpd (reasons why?)
* * * * * wget localhost:background/check_time
Note that the check_time method should actually check the time and not just "do its thing" everytime it is called, since it may well be triggered by anything from the BlackHatLadysAuxillaryAnnualDoSPicnic to TheGoogleSpider