class

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

new(at : Time, &block)

Execute the block at the moment of time.

Source
new(span : Time::Span, &block)

Execute the block in some time span.

Source

Instance methods

at

When the timer is scheduled to be triggered at.

Source
at=(at : Time)

When the timer is scheduled to be triggered at.

Source
cancel

Cancel this timer.

Source
cancelled?

Whether is the timer cancelled.

Source
completed?

Whether is the timer already triggered.

Source
postpone(by : Time::Span)

Postpone the execution by a time span.

Source
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.

Source
trigger

Trigger the execution immediately.

Source