forked from sniperHW/distri.lua
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtimer.lua
More file actions
76 lines (69 loc) · 1.48 KB
/
Copy pathtimer.lua
File metadata and controls
76 lines (69 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
local MinHeap = require "lua.minheap"
local Sche = require "lua.sche"
local timer = {
minheap,
}
function timer:new(runImmediate,tickinterval)
local o = {}
setmetatable(o, self)
self.__index = self
o.minheap = MinHeap.New()
o.tickinterval = tickinterval or 1
if runImmediate then
Sche.SpawnAndRun(function () o:Run() end)
end
return o
end
function timer:Register(callback,ms,...)
local t = {}
t.callback = callback
t.ms = ms
t.index = 0
t.timeout = C.GetSysTick() + ms
t.arg = table.pack(...)
t.timer = self
self.minheap:Insert(t)
return self,t
end
function timer:Remove(t)
if t.timer ~= self or t.invaild then
return false
else
t.invaild = true
return true
end
end
function timer:Stop()
self.stop = true
end
function timer:Run()
if self.running then
return "timer already running"
end
local timer = self.minheap
self.stop = false
while true do
local now = C.GetSysTick()
while not self.stop and timer:Min() ~= 0 and timer:Min() <= now do
t = timer:PopMin()
if not t.invaild then
local status,ret = pcall(t.callback,table.unpack(t.arg))
if not status then
local err = ret
CLog.SysLog(CLog.LOG_ERROR,"timer error:" .. err)
else
if ret == nil then
self:Register(t.callback,t.ms,table.unpack(t.arg))
end
end
end
end
if self.stop then
return nil
end
Sche.Sleep(self.tickinterval)
end
end
return {
New = function (runImmediate,tickinterval) return timer:new(runImmediate,tickinterval) end
}