1
+ import time
1
2
from datetime import timedelta
2
3
from pyres import ResQ , safe_str_to_class
3
4
from pyres import failure
@@ -31,6 +32,8 @@ def __init__(self, queue, payload, resq, worker=None):
31
32
self .resq = resq
32
33
self ._worker = worker
33
34
35
+ self .enqueue_timestamp = self ._payload .get ("enqueue_timestamp" )
36
+
34
37
# Set the default back end, jobs can override when we import them
35
38
# inside perform().
36
39
failure .backend = RedisBackend
@@ -43,6 +46,20 @@ def perform(self):
43
46
"""This method converts payload into args and calls the ``perform``
44
47
method on the payload class.
45
48
49
+ Before calling ``perform``, a ``before_perform`` class method
50
+ is called, if it exists. It takes a dictionary as an argument;
51
+ currently the only things stored on the dictionary are the
52
+ args passed into ``perform`` and a timestamp of when the job
53
+ was enqueued.
54
+
55
+ Similarly, an ``after_perform`` class method is called after
56
+ ``perform`` is finished. The metadata dictionary contains the
57
+ same data, plus a timestamp of when the job was performed, a
58
+ ``failed`` boolean value, and if it did fail, a ``retried``
59
+ boolean value. This method is called after retry, and is
60
+ called regardless of whether an exception is ultimately thrown
61
+ by the perform method.
62
+
46
63
#@ add entry_point loading
47
64
48
65
"""
@@ -51,11 +68,29 @@ def perform(self):
51
68
payload_class .resq = self .resq
52
69
args = self ._payload .get ("args" )
53
70
71
+ metadata = dict (args = args )
72
+ if self .enqueue_timestamp :
73
+ metadata ["enqueue_timestamp" ] = self .enqueue_timestamp
74
+
75
+ before_perform = getattr (payload_class , "before_perform" , None )
76
+ if before_perform :
77
+ before_perform (metadata )
78
+
79
+ metadata ["failed" ] = False
80
+ metadata ["perform_timestamp" ] = time .time ()
54
81
try :
55
82
return payload_class .perform (* args )
56
83
except :
84
+ metadata ["failed" ] = True
57
85
if not self .retry (payload_class , args ):
86
+ metadata ["retried" ] = False
58
87
raise
88
+ else :
89
+ metadata ["retried" ] = True
90
+ finally :
91
+ after_perform = getattr (payload_class , "after_perform" , None )
92
+ if after_perform :
93
+ after_perform (metadata )
59
94
60
95
def fail (self , exception ):
61
96
"""This method provides a way to fail a job and will use whatever
0 commit comments