util/timer.lua

1
-- Prosody IM
2
-- Copyright (C) 2008-2010 Matthew Wild
3
-- Copyright (C) 2008-2010 Waqas Hussain
4
-- 
5
-- This project is MIT/X11 licensed. Please see the
6
-- COPYING file in the source package for more information.
7
--
8
 
9
 
10
local ns_addtimer = require "net.server".addtimer;
11
local event = require "net.server".event;
12
local event_base = require "net.server".event_base;
13
 
14
local math_min = math.min
15
local math_huge = math.huge
16
local get_time = require "socket".gettime;
17
local t_insert = table.insert;
18
local t_remove = table.remove;
19
local ipairs, pairs = ipairs, pairs;
20
local type = type;
21
 
22
local data = {};
23
local new_data = {};
24
 
25
module "timer"
26
 
27
local _add_task;
28
if not event then
29
	function _add_task(delay, func)
30
		local current_time = get_time();
31
		delay = delay + current_time;
32
		if delay >= current_time then
33
			t_insert(new_data, {delay, func});
34
		else
35
			func();
36
		end
37
	end
38
 
39
	ns_addtimer(function()
40
		local current_time = get_time();
41
		if #new_data > 0 then
42
			for _, d in pairs(new_data) do
43
				t_insert(data, d);
44
			end
45
			new_data = {};
46
		end
47
		
48
		local next_time = math_huge;
49
		for i, d in pairs(data) do
50
			local t, func = d[1], d[2];
51
			if t <= current_time then
52
				data[i] = nil;
53
				local r = func(current_time);
54
				if type(r) == "number" then
55
					_add_task(r, func);
56
					next_time = math_min(next_time, r);
57
				end
58
			else
59
				next_time = math_min(next_time, t - current_time);
60
			end
61
		end
62
		return next_time;
63
	end);
64
else
65
	local EVENT_LEAVE = (event.core and event.core.LEAVE) or -1;
66
	function _add_task(delay, func)
67
		local event_handle;
68
		event_handle = event_base:addevent(nil, 0, function ()
69
			local ret = func();
70
			if ret then
71
				return 0, ret;
72
			elseif event_handle then
73
				return EVENT_LEAVE;
74
			end
75
		end
76
		, delay);
77
	end
78
end
79
 
80
add_task = _add_task;
81
 
82
return _M;