timer
Timer
A versatile timer module utilizing Crystal scheduler.
About
Timer
class makes it easy to execute code at some later moment of time. It is fast, performant and reliable.
Installation
- Add the dependency to your
shard.yml
:
dependencies:
timer:
github: vladfaust/timer.cr
version: ~> 0.1.0
- Run
shards install
This shard follows Semantic Versioning v2.0.0, so check releases and change the version
accordingly. Note that until Crystal is official released, this shard would be in beta state (0.*.*
), with every minor release is breaking. For example, 0.1.0
→ 0.2.0
is considered breaking and 0.1.0
→ 0.1.1
is not.
Usage
Basic example:
require "timer"
Timer.new(1.second) do
puts "Triggered"
end
sleep # Will print "Triggered" after 1 second
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, but note that the latter has bigger
performance impact and should only be used when rescheduling to an earlier 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)
# Worse performance than `#postpone`, but still works
timer.reschedule(Time.utc_now + 6.minutes)
# OK, will trigger in 1 minute from now (i.e. eariler)
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 be triggered immediately after given control by the Crystal scheduler.
You can also #trigger
the timer immediately (still calling the block in
another fiber), or #cancel
it completely.
Development
crystal spec
and you're good to go.
Contributing
- Fork it (https://github.com/vladfaust/timer.cr/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'feat: some feature'
) using Conventional Commits specs - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- Vlad Faust - creator and maintainer