On 02/26/2010 08:50 PM, Nick Brown wrote:
> What is the best way to schedule something for delayed asynchronous
> execution? Basically, I want to say "in 20 seconds, execute this
> function / block / proc / lambda / webhook or whatever".
> 
> Also: this will be used by a rack-based web app, so I need a solution
> that will keep working if Passenger restarts instances of the
> application. Would a Thread.new(delay) {|delay| sleep delay; ...} type
> of solution work in such a scenario? Does using Thread like this consume
> lots of memory?
> 
> How have you solved this in the past? I would like to avoid installing
> daemons if possible.
> 
> I was thinking of doing something like below, but I'm not sure it will
> be reliable in a web app environment:
> 
> def call_async(code, delay=0)
>   Thread.new(delay, code) {|d,c| sleep d; c.call}
> end

Probably not - at least if you do not have control over the process. 
For a one off solution you could do

def execute_delayed(sec,&b)
   fork do
     $stdin.close
     $stdout.close
     $stderr.close
     sleep sec
     b.call
   end
end

Demonizing the child is probably also a good idea.  If you want to 
schedule recurring tasks you probably want to use a more robust solution 
/ framework.

Kind regards

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/