Creating a timer using Lua

I would like to create a timer using Lua so that I can specify a callback function that will start in X seconds.

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

Greetings.

+8
source share
5 answers

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) 

Exit:

 1 2 
+5
source

If milisecond accuracy is not needed, you can simply go for a coroutine solution that you periodically resume, for example, at the end of the main loop. For instance:

 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 can use any other alternatives suggested in the Lua-users Wiki

+7
source

If this is acceptable to you, you can try LuaNode . The following code sets a timer:

 setInterval(function() console.log("I run once a minute") end, 60000) process:loop() 
+1
source

use Script.SetTimer (interval, callbackFunction)

+1
source

After reading this thread and others, I decided to go with the 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 
0
source

Source: https://habr.com/ru/post/888969/


All Articles