On 04.12.2008 02:59, Poncho Quintanilla wrote:
> I'm trying to schedule some task using ruby threads
> 
> This work great:
> 
> t = Thread.new do
>   while true do
>     puts "Starting new job at #{Time.now}"
>     do_something
>     sleep 3
>   end
> end
> t.join
> 
> But when the task take a long, like:
> 
> def do_something
>   puts "doing something at#{Time.now}"
>   sleep(rand(3))
> end
> 
> I cant get the "Starting new job" message appears in regular intervals
> of 3 seconds. What I'm missing?

You're sleeping 3 seconds plus whatever rand(3) returns in your thread - 
so the intervals have varying length.  Basically in your code you do not 
use threads properly because there is just one thread active (main 
thread joins t and just sits there and waits for t to complete).

You probably rather wanted this

loop do
   puts "Starting new job at #{Time.now}"
   Thread.new do
     do_something
   end
   sleep 3
end

Note, since you have an infinite loop anyway you do not need to join the 
thread.

Cheers

	robert