使用Lua创建计时器

Gol*_*les 8 lua timer

我想用Lua创建一个计时器,我可以指定一个在X秒过后触发的回调函数.

实现这一目标的最佳方法是什么?(我需要从网络服务器下载一些数据,每小时解析一次或两次)

干杯.

jpj*_*obs 7

如果不需要毫秒精度,你可以选择定期恢复的协同解决方案,就像在主循环结束时一样,如下所示:

require 'socket' -- for having a sleep function ( could also use os.execute(sleep 10))
timer = function (time)
    local init = os.time()
    local diff=os.difftime(os.time(),init)
    while diff<time do
        coroutine.yield(diff)
        diff=os.difftime(os.time(),init)
    end
    print( 'Timer timed out at '..time..' seconds!')
end
co=coroutine.create(timer)
coroutine.resume(co,30) -- timer starts here!
while coroutine.status(co)~="dead" do
    print("time passed",select(2,coroutine.resume(co)))
    print('',coroutine.status(co))
    socket.sleep(5)
end
Run Code Online (Sandbox Code Playgroud)

这使用了LuaSocket中的sleep函数,你可以使用Lua-users Wiki上建议的任何其他替代方法


Joh*_*nck 5

试试lalarm这里:http: //www.tecgraf.puc-rio.br/~lhf/ftp/lua/

示例(基于src/test.lua):

-- alarm([secs,[func]])
alarm(1, function() print(2) end); print(1)
Run Code Online (Sandbox Code Playgroud)

输出:

1
2
Run Code Online (Sandbox Code Playgroud)