Reputation: 513
Is it possible to do a native timer in Ruby?
i.e. command, then another command after X time.
Upvotes: 1
Views: 137
Reputation: 19221
As suggested by @Amadan, you could create a new thread for a delayed task.
...But, be aware that the task will NOT execute if your main thread exits (if your app is finished).
In such a case, you might need to call Thread#join
before your main code exits.
In the following script, the main script is finished before the thread had time to complete - the word 'bye' would never be printed:
Thread.new {puts 'hi!'; sleep 5; puts 'bye'}
depending on your application and design, you might want to move the app's execution to a sub-thread, or perhaps write an event reactor to run everything asynchronously.
This way you could make sure the task is run even if the application is done before the task is finished.
For instance, suppose your code takes 2 seconds to complete a task and print out the output:
app_thread = Thread.new do
sleep 2
puts "app is done!"
end
and your task takes 5 seconds:
task_thread = Thread.new {sleep 5; puts 'task is done.'}
You could make sure the process doesn't exit before both the task and the app are finished by adding:
app_thread.join
task_thread.join
Try the following demo code as a script with and without the join
statements and see what happens:
app_thread = Thread.new do
sleep 2
puts "app is done!"
end
task_thread = Thread.new {sleep 5; puts 'task is done.'}
app_thread.join
task_thread.join
If you're looking into event reactors and timers, you might look into the EventMachine code or - if you're looking for a pure ruby example, you can dig into the Plezi framework's code which also supports timers to some extent (using the run_every
and run_after
methods here, although they are based off the event's management and the reactor)
Upvotes: 2