Search code examples
rubymultithreadingschedule

How to start a new thread every x seconds


I want to start a new thread every x seconds in Ruby, but wasn´t able to figure it out.

Usually the thread execution takes longer then the x seconds, all I managed was something that starts a new thread after the previous one finished. So I want to start a new thread after x seconds, now matter how many previous threads are still running.

Any ideas?


Solution

  • threads = [] # array of Thread in case you need to do something with all the Threads
                 # like threads.each { |t| t.join }
    
    1.upto(5) do |n|
      threads << Thread.new { puts "Thread #{n}!" }
      sleep 1   # or more seconds if need it
    end