Comparison

util/timer.lua @ 2095:3256c5d00901

util.timer: Use libevent for lightweight timers if available and configured (use_libevent option)
author Matthew Wild <mwild1@gmail.com>
date Sat, 21 Nov 2009 02:40:21 +0000
parent 1871:838d1317bca4
child 2098:a1ad06f1c090
comparison
equal deleted inserted replaced
2094:c69cb5c171e0 2095:3256c5d00901
6 -- COPYING file in the source package for more information. 6 -- COPYING file in the source package for more information.
7 -- 7 --
8 8
9 9
10 local ns_addtimer = require "net.server".addtimer; 10 local ns_addtimer = require "net.server".addtimer;
11 local event = require "net.server".event;
12
11 local get_time = os.time; 13 local get_time = os.time;
12 local t_insert = table.insert; 14 local t_insert = table.insert;
13 local t_remove = table.remove; 15 local t_remove = table.remove;
14 local ipairs, pairs = ipairs, pairs; 16 local ipairs, pairs = ipairs, pairs;
15 local type = type; 17 local type = type;
17 local data = {}; 19 local data = {};
18 local new_data = {}; 20 local new_data = {};
19 21
20 module "timer" 22 module "timer"
21 23
22 local function _add_task(delay, func) 24 local _add_task;
23 local current_time = get_time(); 25 if not event then
24 delay = delay + current_time; 26 function _add_task(delay, func)
25 if delay >= current_time then 27 local current_time = get_time();
26 t_insert(new_data, {delay, func}); 28 delay = delay + current_time;
27 else func(); end 29 if delay >= current_time then
30 t_insert(new_data, {delay, func});
31 else
32 func();
33 end
34 end
35
36 ns_addtimer(function()
37 local current_time = get_time();
38 if #new_data > 0 then
39 for _, d in pairs(new_data) do
40 t_insert(data, d);
41 end
42 new_data = {};
43 end
44
45 for i, d in pairs(data) do
46 local t, func = d[1], d[2];
47 if t <= current_time then
48 data[i] = nil;
49 local r = func(current_time);
50 if type(r) == "number" then _add_task(r, func); end
51 end
52 end
53 end);
54 else
55 local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1;
56 function _add_task(delay, func)
57 event.base:addevent(nil, event.EV_TIMEOUT, function ()
58 local ret = func();
59 if ret then
60 _add_task(ret, func);
61 else
62 return EVENT_LEAVE;
63 end
64 end
65 , delay);
66 end
28 end 67 end
29 68
30 add_task = _add_task; 69 add_task = _add_task;
31 70
32 ns_addtimer(function()
33 local current_time = get_time();
34 if #new_data > 0 then
35 for _, d in pairs(new_data) do
36 t_insert(data, d);
37 end
38 new_data = {};
39 end
40
41 for i, d in pairs(data) do
42 local t, func = d[1], d[2];
43 if t <= current_time then
44 data[i] = nil;
45 local r = func(current_time);
46 if type(r) == "number" then _add_task(r, func); end
47 end
48 end
49 end);
50
51 return _M; 71 return _M;