1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 """
17 Action slass for gofer agent.
18 """
19
20 import inspect
21 from gofer.collator import Collator
22 from datetime import datetime as dt
23 from datetime import timedelta
24 from logging import getLogger
25
26 log = getLogger(__name__)
30 """
31 @cvar functions: The list of decorated functions.
32 """
33 functions = {}
34
35 @classmethod
36 - def add(cls, fn, interval):
38
39 @classmethod
55
56 @classmethod
58 """
59 Clear the list of actions.
60 """
61 cls.functions = {}
62
65 """
66 Action decorator.
67 """
68 def decorator(fn):
69 Actions.add(fn, interval)
70 return fn
71 return decorator
72
75 """
76 Abstract recurring action (base).
77 @ivar target: The action target.
78 @type target: (method|function)
79 @keyword interval: The run interval.
80 One of:
81 - days
82 - seconds
83 - minutes
84 - hours
85 - weeks
86 @ivar last: The last run timestamp.
87 @type last: datetime
88 """
89
91 """
92 @param target: The action target.
93 @type target: (method|function)
94 @param interval: The run interval (minutes).
95 @type interval: timedelta
96 """
97 self.target = target
98 for k,v in interval.items():
99 interval[k] = int(v)
100 self.interval = timedelta(**interval)
101 self.last = dt(1900, 1, 1)
102
104 """
105 Get action name. Default to class name.
106 @return: The action name.
107 @rtype: str
108 """
109 t = self.target
110 if inspect.ismethod(t):
111 cls = t.im_class
112 else:
113 cls = t.__module__
114 method = t.__name__
115 return '%s.%s()' % (cls, method)
116
119
121 try:
122 next = self.last+self.interval
123 now = dt.utcnow()
124 if next < now:
125 self.last = now
126 log.debug('perform "%s"', self.name())
127 self.target()
128 except Exception, e:
129 log.exception(e)
130