Timers/Intervals in Crystal Lang
Asked Answered
R

2

7

Is there a timer or interval function in Crystal?

I checked the docs for a timer, interval, and under the Time class, but did not see anything.

Something like setInterval() or setTimeout() from JavaScript?

Raleighraley answered 19/3, 2018 at 9:2 Comment(1)
use can use this libraries github.com/veelenga/awesome-crystal#schedulingCassette
D
8

For timeout there's delay. Please be aware that the API for this isn't finalized and might get changed in a future release or even temporarily removed again.

For interval there's currently nothing that guarantees exact timings, but if that's no concern and an approximate interval is enough it's as simple to do as

spawn do
  loop do
    sleep INTERVAL
    do_regular_work
  end
end

sleep # Or some other workload, when the main fiber quits so will the program and thus all other fibers.
Democratic answered 19/3, 2018 at 10:16 Comment(2)
Addition: delay is actually an implementation of a future object, so it can return a value and be cancelled. If you don't need these features, you should just use spawn + sleep instead.Beowulf
Note that delay has been removed in the 0.35.0 release: crystal-lang.org/2020/06/09/crystal-0.35.0-released.html (Background: github.com/crystal-lang/crystal/pull/9093 )Stingaree
L
0

https://github.com/hugoabonizio/schedule.cr

require "schedule"

# Print "Hello!" each 2 seconds
Schedule.every(2.seconds) do
  puts "Hello!"
end

sleep
Laina answered 13/12, 2020 at 22:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.