我想实现一个代码,以指定的时间间隔(即每5秒(调用特定的函数。类似于JavaScript中的window.setInterval((方法。
在主线程中有一个game_lop((函数,它将数据打印到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()
我认为这应该使用线程来完成,但我不知道如何做到
谢谢你的帮助。
您可以尝试使用此gem:
rufus调度器
它可能类似于:
require 'rufus-scheduler'
scheduler = Rufus::Scheduler.new
scheduler.in '5s' do
Production.make if ... # some condition is met
game_loop()
end