more Markdown stuff
[synarere.git] / core / timer.py
blob9829562990faf1355f8d5bb0299f72984ff45ecd
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.
5 '''Timer stuff.'''
7 # Import required Python modules.
8 import time
10 # Import required core modules.
11 import var, event
13 # The lowest time when a timer must execute.
14 timer_min = -1
16 def add(name, only_once, func, freq, args=None):
17 '''Add a new timer to be executed every `freq` seconds.'''
19 global timer_min
21 timer = { 'name' : name,
22 'func' : func,
23 'args' : args,
24 'freq' : freq if not only_once else 0,
25 'when' : (time.time() + freq),
26 'active': True }
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)
40 def next_run():
41 '''Return the time the next timer has to be executed.'''
43 global timer_min
45 for timer in var.timers:
46 if timer['when'] < timer_min or timer_min == -1:
47 timer_min = timer['when']
49 return timer_min
51 def run():
52 '''Execute all timers that need to be executed.'''
54 global timer_min
56 for timer in var.timers:
57 if timer['when'] <= time.time():
58 timer['func'](timer['args'])
59 timer_min = -1
61 event.dispatch('OnTimerCallFunction', timer['func'], timer['args'])
63 # If it's scheduled more than once updated its `when`.
64 if timer['freq']:
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.
71 else:
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']]