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.
17 '''Make a new timer.'''
19 timer
= { 'name' : None,
28 def add(name
, only_once
, func
, freq
, args
=None):
29 '''Add a new timer to be executed every `freq` seconds.'''
37 timer
['freq'] = freq
if not only_once
else 0
38 timer
['when'] = (time
.time() + freq
)
39 timer
['active'] = True
41 if timer
['when'] < timer_min
or timer_min
== -1:
42 timer_min
= timer
['when']
44 var
.timers
.append(timer
)
46 def delete(func
, args
=None):
47 '''Delete all timers with matching `func` and `args`.'''
49 var
.timers
= [timer
for timer
in var
.timers
if timer
['func'] != func
and timer
['args'] != args
]
52 '''Return the time the next timer has to be executed.'''
56 for timer
in var
.timers
:
57 if timer
['when'] < timer_min
or timer_min
== -1:
58 timer_min
= timer
['when']
63 '''Execute all timers that need to be executed.'''
67 for timer
in var
.timers
:
68 if timer
['when'] <= time
.time():
69 timer
['func'](timer
['args'])
72 # If it's scheduled more than once updated its `when`.
74 timer
['when'] = (time
.time() + timer
['freq'])
76 if timer
['when'] < timer_min
or timer_min
== -1:
77 timer_min
= timer
['when']
79 # Otherwise mark it as inactive.
81 timer
['active'] = False
83 # Delete any timers that aren't useful anymore.
84 var
.timers
= [timer
for timer
in var
.timers
if timer
['active']]