Comparison

util/timer.lua @ 6930:58e260832334

util.timer: Keep count of how many timer instances are active
author Kim Alvefur <zash@zash.se>
date Sun, 22 Nov 2015 17:18:29 +0100
parent 6836:9f45f0fe5aef
child 6931:5c2c8aeb4690
comparison
equal deleted inserted replaced
6929:03bc9e197fcc 6930:58e260832334
17 17
18 local _ENV = nil; 18 local _ENV = nil;
19 19
20 local _add_task = server.add_task; 20 local _add_task = server.add_task;
21 21
22 local _active_timers = 0;
22 local h = indexedbheap.create(); 23 local h = indexedbheap.create();
23 local params = {}; 24 local params = {};
24 local next_time = nil; 25 local next_time = nil;
25 local _id, _callback, _now, _param; 26 local _id, _callback, _now, _param;
26 local function _call() return _callback(_now, _id, _param); end 27 local function _call() return _callback(_now, _id, _param); end
44 end 45 end
45 next_time = peek; 46 next_time = peek;
46 if peek ~= nil then 47 if peek ~= nil then
47 return peek - now; 48 return peek - now;
48 end 49 end
50 _active_timers = _active_timers - 1;
49 end 51 end
50 local function add_task(delay, callback, param) 52 local function add_task(delay, callback, param)
51 local current_time = get_time(); 53 local current_time = get_time();
52 local event_time = current_time + delay; 54 local event_time = current_time + delay;
53 55
54 local id = h:insert(callback, event_time); 56 local id = h:insert(callback, event_time);
55 params[id] = param; 57 params[id] = param;
56 if next_time == nil or event_time < next_time then 58 if next_time == nil or event_time < next_time then
57 next_time = event_time; 59 next_time = event_time;
60 _active_timers = _active_timers + 1;
58 _add_task(next_time - current_time, _on_timer); 61 _add_task(next_time - current_time, _on_timer);
59 end 62 end
60 return id; 63 return id;
61 end 64 end
62 local function stop(id) 65 local function stop(id)