Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a timer using Lua

Tags:

timer

lua

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.

like image 890
Goles Avatar asked May 25 '11 02:05

Goles


2 Answers

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

like image 83
jpjacobs Avatar answered Oct 30 '22 19:10

jpjacobs


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
like image 42
John Zwinck Avatar answered Oct 30 '22 18:10

John Zwinck