forked from hacktoolkit/django-htk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.py
80 lines (69 loc) · 2.31 KB
/
tasks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import inspect
import rollbar
class BaseTask(object):
"""Base class for background tasks
Examples:
- Daily or weekly updates
- Drip reminders
- Account status reports
- Shopping cart abandonment reminders
"""
def __init__(self, cooldown_class=None):
# set cooldown_class
from htk.cachekeys import TaskCooldown
if inspect.isclass(cooldown_class) and issubclass(cooldown_class, TaskCooldown):
self.cooldown_class = cooldown_class
else:
self.cooldown_class = TaskCooldown
def get_cooldown_class_prekey(self, user):
prekey = user.id
return prekey
def has_cooldown(self, user):
"""Checks whether cooldown timer is still going for `user`
"""
prekey = self.get_cooldown_class_prekey(user)
c = self.cooldown_class(prekey)
_has_cooldown = bool(c.get())
return _has_cooldown
def reset_cooldown(self, user):
"""Resets cooldown timer for this `user`
Returns whether cooldown was reset, False if timer was still running
"""
prekey = self.get_cooldown_class_prekey(user)
c = self.cooldown_class(prekey)
if c.get():
was_reset = False
else:
c.cache_store()
was_reset = True
return was_reset
def get_users(self):
"""Returns a list or QuerySet of User objects
Should be overridden
"""
users = []
return users
def execute(self, user):
"""Workhorse function called by `self.execute_batch`
Can be overriden
"""
pass
def execute_batch(self):
"""Batch execution
"""
users = self.get_users()
for user in users:
try:
if self.has_cooldown(user):
# cooldown has not elapsed yet, don't execute too frequently
pass
else:
self.execute(user)
# cache right after execution or exception, not before
# since each execution costs a non-zero overhead
self.reset_cooldown(user)
except:
extra_data = {
'user' : user,
}
rollbar.report_exc_info(extra_data=extra_data)