Comparison

util/timer.lua @ 6481:dbc72cd1332e

Move timer code out of util.timer and into relevant net.server backends
author daurnimator <quae@daurnimator.com>
date Mon, 20 Oct 2014 16:13:24 -0400
parent 5898:bf9aba718c01
child 6791:e813e8cf6046
comparison
equal deleted inserted replaced
6480:37b12475f648 6481:dbc72cd1332e
7 -- 7 --
8 8
9 local indexedbheap = require "util.indexedbheap"; 9 local indexedbheap = require "util.indexedbheap";
10 local log = require "util.logger".init("timer"); 10 local log = require "util.logger".init("timer");
11 local server = require "net.server"; 11 local server = require "net.server";
12 local math_min = math.min
13 local math_huge = math.huge
14 local get_time = require "socket".gettime; 12 local get_time = require "socket".gettime;
15 local t_insert = table.insert;
16 local pairs = pairs;
17 local type = type; 13 local type = type;
18 local debug_traceback = debug.traceback; 14 local debug_traceback = debug.traceback;
19 local tostring = tostring; 15 local tostring = tostring;
20 local xpcall = xpcall; 16 local xpcall = xpcall;
21 17
22 local data = {};
23 local new_data = {};
24
25 module "timer" 18 module "timer"
26 19
27 local _add_task; 20 local _add_task = server.add_task;
28 if not server.event then
29 function _add_task(delay, callback)
30 local current_time = get_time();
31 delay = delay + current_time;
32 if delay >= current_time then
33 t_insert(new_data, {delay, callback});
34 else
35 local r = callback(current_time);
36 if r and type(r) == "number" then
37 return _add_task(r, callback);
38 end
39 end
40 end
41
42 server._addtimer(function()
43 local current_time = get_time();
44 if #new_data > 0 then
45 for _, d in pairs(new_data) do
46 t_insert(data, d);
47 end
48 new_data = {};
49 end
50
51 local next_time = math_huge;
52 for i, d in pairs(data) do
53 local t, callback = d[1], d[2];
54 if t <= current_time then
55 data[i] = nil;
56 local r = callback(current_time);
57 if type(r) == "number" then
58 _add_task(r, callback);
59 next_time = math_min(next_time, r);
60 end
61 else
62 next_time = math_min(next_time, t - current_time);
63 end
64 end
65 return next_time;
66 end);
67 else
68 local event = server.event;
69 local event_base = server.event_base;
70 local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1;
71
72 function _add_task(delay, callback)
73 local event_handle;
74 event_handle = event_base:addevent(nil, 0, function ()
75 local ret = callback(get_time());
76 if ret then
77 return 0, ret;
78 elseif event_handle then
79 return EVENT_LEAVE;
80 end
81 end
82 , delay);
83 end
84 end
85
86 --add_task = _add_task; 21 --add_task = _add_task;
87 22
88 local h = indexedbheap.create(); 23 local h = indexedbheap.create();
89 local params = {}; 24 local params = {};
90 local next_time = nil; 25 local next_time = nil;