Mercurial > prosody-hg
comparison util/timer.lua @ 6935:d12917643e65
Merge
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Tue, 24 Nov 2015 10:45:48 +0000 |
| parents | f5fd2c5cdf28 |
| children | 17e275e8bd79 |
comparison
equal
deleted
inserted
replaced
| 6934:5d913559d092 | 6935:d12917643e65 |
|---|---|
| 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 _server_timer; | |
| 23 local _active_timers = 0; | |
| 22 local h = indexedbheap.create(); | 24 local h = indexedbheap.create(); |
| 23 local params = {}; | 25 local params = {}; |
| 24 local next_time = nil; | 26 local next_time = nil; |
| 25 local _id, _callback, _now, _param; | 27 local _id, _callback, _now, _param; |
| 26 local function _call() return _callback(_now, _id, _param); end | 28 local function _call() return _callback(_now, _id, _param); end |
| 40 if success and type(err) == "number" then | 42 if success and type(err) == "number" then |
| 41 h:insert(_callback, err + now, _id); -- re-add | 43 h:insert(_callback, err + now, _id); -- re-add |
| 42 params[_id] = _param; | 44 params[_id] = _param; |
| 43 end | 45 end |
| 44 end | 46 end |
| 45 next_time = peek; | 47 |
| 46 if peek ~= nil then | 48 if peek ~= nil and _active_timers > 1 and peek == next_time then |
| 49 -- Another instance of _on_timer already set next_time to the same value, | |
| 50 -- so it should be safe to not renew this timer event | |
| 51 peek = nil; | |
| 52 else | |
| 53 next_time = peek; | |
| 54 end | |
| 55 | |
| 56 if peek then | |
| 57 -- peek is the time of the next event | |
| 47 return peek - now; | 58 return peek - now; |
| 48 end | 59 end |
| 60 _active_timers = _active_timers - 1; | |
| 49 end | 61 end |
| 50 local function add_task(delay, callback, param) | 62 local function add_task(delay, callback, param) |
| 51 local current_time = get_time(); | 63 local current_time = get_time(); |
| 52 local event_time = current_time + delay; | 64 local event_time = current_time + delay; |
| 53 | 65 |
| 54 local id = h:insert(callback, event_time); | 66 local id = h:insert(callback, event_time); |
| 55 params[id] = param; | 67 params[id] = param; |
| 56 if next_time == nil or event_time < next_time then | 68 if next_time == nil or event_time < next_time then |
| 57 next_time = event_time; | 69 next_time = event_time; |
| 58 _add_task(next_time - current_time, _on_timer); | 70 if _server_timer then |
| 71 _server_timer:close(); | |
| 72 _server_timer = nil; | |
| 73 else | |
| 74 _active_timers = _active_timers + 1; | |
| 75 end | |
| 76 _server_timer = _add_task(next_time - current_time, _on_timer); | |
| 59 end | 77 end |
| 60 return id; | 78 return id; |
| 61 end | 79 end |
| 62 local function stop(id) | 80 local function stop(id) |
| 63 params[id] = nil; | 81 params[id] = nil; |
