initial commit
[synarere.git] / core / timer.py
blobb0f5dde42ac2eaad7f6adebbb417ef9cfb071055
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
13 # The lowest time when a timer must execute.
14 timer_min = -1
16 def new():
17 '''Make a new timer.'''
19 timer = { 'name' : None,
20 'func' : None,
21 'args' : None,
22 'freq' : 0,
23 'when' : 0,
24 'active' : False }
26 return timer
28 def add(name, only_once, func, freq, args=None):
29 '''Add a new timer to be executed every `freq` seconds.'''
31 global timer_min
33 timer = new()
34 timer['name'] = name
35 timer['func'] = func
36 timer['args'] = args
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]
51 def next_run():
52 '''Return the time the next timer has to be executed.'''
54 global timer_min
56 for timer in var.timers:
57 if timer['when'] < timer_min or timer_min == -1:
58 timer_min = timer['when']
60 return timer_min
62 def run():
63 '''Execute all timers that need to be executed.'''
65 global timer_min
67 for timer in var.timers:
68 if timer['when'] <= time.time():
69 timer['func'](timer['args'])
70 timer_min = -1
72 # If it's scheduled more than once updated its `when`.
73 if timer['freq']:
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.
80 else:
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']]