Reputation: 9499
I am new to ruby and trying to work around threads
Let's say I have a method which I want to run every x seconds as follows
def say_hello
puts 'hello world'
end
I am trying to run it as follows
Thread.new do
while true do
say_hello
sleep(5)
end
end
But when I run the script, nothing is displayed on the console. What am I missing? Thanks!
Upvotes: 8
Views: 5903
Reputation: 9693
You are creating the Thread object, but you are not waiting for it to finish its execution, try with:
Thread.new do
while true do
say_hello
sleep(5)
end
end.join
Upvotes: 5
Reputation: 783
Try
t1 = Thread.new do
while true do
say_hello
sleep(5)
end
end
t1.join
Upvotes: 0
Reputation: 2672
The main thread is exiting before your thread can run. Use the join method to make the current thread wait for the say_hello
thread to finish executing (though it never will).
t = Thread.new do
while true do
say_hello
sleep(5)
end
end
t.join
Upvotes: 8