Timer
Inherits Reference < Object
Versatile Timer class which relies on Crystal scheduler.
Basic example:
Timer.new(1.second) do
puts "1 second has passed!"
end
sleep
Example with select:
channel = Channel(Nil).new
select
when channel.receive
puts "Never happens"
when Timer.new(1.second)
puts "Timeout!"
end
sleep # Will print "Timeout!" after 1 second
You can #postpone and #reschedule a timer. The latter has bigger
performance impact if rescheduling at an earlier moment of time.
at = Time.utc_now + 5.minutes
timer = Timer.new(at) do
puts "Triggered"
end
# OK, will trigger in 6 minutes from now
timer.postpone(1.minute)
# ditto
timer.reschedule(Time.utc_now + 6.minutes)
# Worse performance but still acceptable
timer.reschedule(Time.utc_now + 1.minute)
Note that a timer can be scheduled at a moment in the past, which means that it would run immediately after given control by the Crystal scheduler.
You can also #trigger a timer (still calling the block in another fiber) or
#cancel it completely.
Constructors
Instance methods
reschedule(at : Time)
Reschedule the timer at desired time.
NOTE: Rescheduling at earlier time has bigger performance impact than at a moment in the future.