A versatile timer module utilizing Crystal scheduler.
Timer class makes it easy to execute code at some later moment of time. It is fast, performant and reliable.
- Add the dependency to your
dependencies: timer: github: vladfaust/timer.cr version: ~> 0.1.0
This shard follows Semantic Versioning v2.0.0, so check releases and change the
version accordingly. Note that until Crystal is officially released, this shard would be in beta state (
0.*.*), with every minor release considered breaking. For example,
0.2.0 is breaking and
0.1.1 is not.
require "timer" Timer.new(1.second) do puts "Triggered" end sleep # Will print "Triggered" after 1 second
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
#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.
crystal spec and you're good to go.
- 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
- Vlad Faust - creator and maintainer