-
Notifications
You must be signed in to change notification settings - Fork 0
/
lcron.lua
49 lines (38 loc) · 897 Bytes
/
lcron.lua
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
local _M = {}
local core = require("lcronc")
local os = os
local error = error
local pairs = pairs
local table = table
local items = {}
_M.add = function(name, expr, callback)
if items[name] then
error("cron already exist: " .. name)
end
local obj = core.expr(expr)
local item = {
expr = obj,
name = name,
next = obj:next(os.time()),
callback = callback
}
items[name] = item
end
_M.update = function()
local now = os.time()
-- ref all to avoid delete in callback
local refs = {}
for _, v in pairs(items) do
table.insert(refs, v)
end
for i, v in ipairs(refs) do
if now >= v.next then
v.next = v.expr:next(now)
v.callback()
end
end
end
_M.delete = function(name)
items[name] = nil
end
return _M