Skip to content

vladfaust/timer.cr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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