dkimot
dkimot

Reputation: 2289

Timers/Intervals in Crystal Lang

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?

Upvotes: 7

Views: 1013

Answers (2)

Peter Bauer
Peter Bauer

Reputation: 294

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

require "schedule"

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

sleep

Upvotes: 0

Jonne Haß
Jonne Haß

Reputation: 4857

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.

Upvotes: 8

Related Questions