From: Sam Duncan Date: 2011-10-11T07:39:05+09:00 Subject: Re: scheduler and thread On 11/10/11 11:20, lover ruby wrote: > Hi > I want to make a scheduler like this. > > module Timer > def Timer.repeat_every(interval) > Thread.new do > loop do > start_time = Time.now > yield > elapsed = Time.now - start_time > sleep([interval - elapsed, 0].max) > end > end.join > end > end > > Timer.repeat_every(5) do > puts Time.now.to_i > end > > puts "Doing other stuff..." > --------------------------------------------------- > But it never prints out "Doing other stuff..." > > How can I make it print out like > "Doing other stuff..." > 1318284723 > 1318284728 > 1318284733 > > Thanks Try this; module Timer @timer = nil def Timer.repeat_every(interval) @timer = Thread.new do loop do start_time = Time.now yield elapsed = Time.now - start_time sleep([interval - elapsed, 0].max) end end end def Timer.stop unless @timer.nil? @timer.kill @timer.join(1) # don't hang forever @timer = nil end end end Timer.repeat_every(5) do puts Time.now.to_i end puts "Doing other stuff..." sleep 10 puts "Stopping timer" Timer.stop As far as I can tell your execution is hanging on the join which will never return as the timer thread is in an infinite loop =] Hope that helps Sam