Creating a timer using Lua

2019-02-09 08:48发布

I would like to create a timer using Lua, in a way that I could specify a callback function to be triggered after X seconds have passed.

What would be the best way to achieve this? ( I need to download some data from a webserver that will be parsed once or twice an hour )

Cheers.

标签: timer lua
5条回答
Melony?
2楼-- · 2019-02-09 09:07

If it's acceptable for you, you can try LuaNode. The following code sets a timer:

setInterval(function()
    console.log("I run once a minute")
end, 60000)
process:loop()
查看更多
劫难
3楼-- · 2019-02-09 09:21

use Script.SetTimer(interval, callbackFunction)

查看更多
看我几分像从前
4楼-- · 2019-02-09 09:26

Try lalarm, here: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/

Example (based on src/test.lua):

-- alarm([secs,[func]])
alarm(1, function() print(2) end); print(1)

Output:

1
2
查看更多
唯我独甜
5楼-- · 2019-02-09 09:28

If milisecond accuracy is not needed, you could just go for a coroutine solution, which you resume periodically, like at the end of your main loop, Like this:

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

This uses the sleep function in LuaSocket, you could use any other of the alternatives suggested on the Lua-users Wiki

查看更多
ゆ 、 Hurt°
6楼-- · 2019-02-09 09:28

After reading this thread and others I decided to go with Luv lib. Here is my solution:

uv = require('luv') --luarocks install luv

function set_timeout(timeout, callback)
  local timer = uv.new_timer()
  local function ontimeout()
    uv.timer_stop(timer)
    uv.close(timer)
    callback()
  end
  uv.timer_start(timer, timeout, 0, ontimeout)
  return timer
end


set_timeout(1000, function() print('ok') end) -- time in ms

uv.run() --it will hold at this point until every timer have finished
查看更多
登录 后发表回答