1 # synarere -- a highly modular and stable IRC bot.
2 # Copyright (C) 2010 Michael Rodriguez.
3 # Rights to this code are documented in docs/LICENSE.
7 # Import required Python modules.
10 # Import required core modules.
13 # The lowest time when a timer must execute.
16 def add(name
, only_once
, func
, freq
, args
=None):
17 '''Add a new timer to be executed every `freq` seconds.'''
21 timer
= { 'name' : name
,
24 'freq' : freq
if not only_once
else 0,
25 'when' : (time
.time() + freq
),
28 if timer
['when'] < timer_min
or timer_min
== -1:
29 timer_min
= timer
['when']
31 var
.timers
.append(timer
)
32 event
.dispatch('OnAddTimer', timer
)
34 def delete(func
, args
=None):
35 '''Delete all timers with matching `func` and `args`.'''
37 var
.timers
= [timer
for timer
in var
.timers
if timer
['func'] != func
and timer
['args'] != args
]
38 event
.dispatch('OnTimerDelete', func
, args
)
41 '''Return the time the next timer has to be executed.'''
45 for timer
in var
.timers
:
46 if timer
['when'] < timer_min
or timer_min
== -1:
47 timer_min
= timer
['when']
52 '''Execute all timers that need to be executed.'''
56 for timer
in var
.timers
:
57 if timer
['when'] <= time
.time():
58 timer
['func'](timer
['args'])
61 event
.dispatch('OnTimerCallFunction', timer
['func'], timer
['args'])
63 # If it's scheduled more than once updated its `when`.
65 timer
['when'] = (time
.time() + timer
['freq'])
67 if timer
['when'] < timer_min
or timer_min
== -1:
68 timer_min
= timer
['when']
70 # Otherwise mark it as inactive.
72 timer
['active'] = False
74 # Delete any timers that aren't useful anymore.
75 var
.timers
= [timer
for timer
in var
.timers
if timer
['active']]