Timers/Intervals 在 Crystal 朗

Timers/Intervals in Crystal Lang

Crystal有定时器或间隔功能吗?

我检查了文档中的计时器、间隔和时间 class,但没有看到任何内容。

setInterval()setTimeout() 来自 JavaScript?

超时有 delay。请注意,此 API 尚未最终确定,可能会在未来的版本中更改,甚至可能会再次暂时删除。

对于间隔,目前没有任何东西可以保证准确的时间,但如果这不是问题并且一个近似的间隔就足够了,那就很简单了

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.

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

require "schedule"

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

sleep