dopplesoldner
dopplesoldner

Reputation: 9499

ruby - start a thread

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

Answers (3)

rorra
rorra

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

Se Won Jang
Se Won Jang

Reputation: 783

Try

t1 = Thread.new do
    while true do
        say_hello
        sleep(5)
    end
end

t1.join

Upvotes: 0

axblount
axblount

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

Related Questions