如何在Ruby中实现简单的时间间隔?
我想实现一个以指定时间间隔(即每 5 秒)调用特定函数的代码。类似于 JavaScript 中的 window.setInterval() 方法。
主线程中有 game_loop() 函数,它将数据打印到 STDOUT 并等待用户的键盘输入。其简化版本如下:
def game_loop
k = ""
UI.refresh
while not k == "q"
k = UI.read_key # STDIN.getch() is implemented inside of this function
case k
when "p"
# do something
when "f"
# do something else
end
end
end
现在我想添加一个代码,如果满足条件,该代码会在每个定义的时间间隔调用另一个函数。示例:
sleep 5
Production.make if ... # some condition is met
# return to game_loop()
我认为这应该使用线程来完成,但我不知道如何做到这一点。
感谢您的帮助。
I would like to implement a code that calls specific function at specified time intervals i.e. each 5 seconds. Something similar to window.setInterval() method in JavaScript.
There is game_loop() function at the main thread that prints data to STDOUT and waits for keyboard key input from the user. Simplified version of it below:
def game_loop
k = ""
UI.refresh
while not k == "q"
k = UI.read_key # STDIN.getch() is implemented inside of this function
case k
when "p"
# do something
when "f"
# do something else
end
end
end
Now I would like to add a code which calls another function at per-defined time interval if condition is met. Example:
sleep 5
Production.make if ... # some condition is met
# return to game_loop()
I assume this should be done using threads, but I do not have an idea how to do it.
Thank you for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用此宝石:
rufus-scheduler
这会是:
You can try using this gem:
rufus-scheduler
It would be something like: