timer

A versatile timer module
0.1.1 Latest release released
vladfaust/timer.cr
4 2 5
Vlad Faust

Timer

Built with Crystal Build status API Docs Releases Awesome vladfaust.com Patrons count Gitter chat

A versatile timer module utilizing Crystal scheduler.

Become Patron

About

Timer class makes it easy to execute code at some later moment of time. It is fast, performant and reliable.

Installation

  1. Add the dependency to your shard.yml:
dependencies:
  timer:
    github: vladfaust/timer.cr
    version: ~> 0.1.0
  1. Run shards install

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.1.00.2.0 is breaking and 0.1.00.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. 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.

Development

crystal spec and you're good to go.

Contributing

  1. Fork it (https://github.com/vladfaust/timer.cr/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'feat: some feature') using Conventional Commits specs
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

timer:
  github: vladfaust/timer.cr
  version: ~> 0.1.1
License MIT
Crystal 0.27.2

Authors

Dependencies 0

Development Dependencies 0

Dependents 0

Last synced .
search fire star recently