Lua脚本实现类似Timer的功能(使用协程)
在使用LUA脚本语言的过程中,通常有一些需求是希望程序在运行的过程中定期的输出一些变量的状态,统计数据等信息。然而但是,LUA并没有实现好的Timer。由于我最近正在用lua写一些USB设备的功能性测试脚本,所以用到了类似于timer的功能,于是乎东拼西凑了一个类似于timer的小脚本,下面上代码:
--dummy global variables
local i = 0
local j = 0
co_on_timer = coroutine.create(function()
local k = 0
while true do
--do something
print(k, ' Second: ', i, j)
coroutine.yield() --waiting for being activated.
k = k + 1
end
end)
coroutine.resume(co_on_timer)
-- init timer
local timetable = os.date("*t");
local lasttime = os.time(timetable)
while true do
-- dummy, do something
i = i + 1
j = j + 2
timetable = os.date("*t");
local nowtime = os.time(timetable)
local difft = os.difftime(nowtime, lasttime);
if difft > 1.0 then --1 second timer arrived
coroutine.resume(co_on_timer) --activate the timer
lasttime = nowtime --next timer
end
end
实现原理
主要就是利用了lua协程和os.difftime功能。co_on_timer 协程的作用就是等待被主线程激活,激活后做一些事情,然后继续挂起,等待下一次被激活。
主线程的while循环中,每隔一秒钟激活一次co_on_timer协程。如果不到一秒钟,则继续干其他的事情。 其中difft > 1.0中的1.0, 可以指定为其他值,已整秒为单位。如difft > 3.0就表示每隔3秒激活一次timer。
两者配合起来,就实现了类似VC++ MFC中OnTimer的功能。
程序运行效果: