-
Notifications
You must be signed in to change notification settings - Fork 0
/
Job.php
432 lines (375 loc) · 9.87 KB
/
Job.php
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<?php
/**
* OriginPHP Framework
* Copyright 2018 - 2021 Jamiel Sharief.
*
* Licensed under The MIT License
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* @copyright Copyright (c) Jamiel Sharief
* @link https://www.originphp.com
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types = 1);
namespace Origin\Job;
use \ArrayObject;
use Origin\Log\Log;
use Origin\Core\HookTrait;
use Origin\Core\ModelTrait;
use Origin\Security\Security;
use Origin\Core\CallbacksTrait;
use Origin\Job\Engine\BaseEngine;
/**
* (new SendUserWelcomeEmail($user))->dispatch();
* (new SendUserWelcomeEmail($user))->dispatch(['wait' => '+5 minutes']);
*/
/**
* Add the execute method to your class
* @method bool execute() This will be called by dispatch
*/
class Job
{
use ModelTrait;
use HookTrait;
use CallbacksTrait;
/**
* This is the display name for the job
*
* @example SendWelcomeEmail
*
* @var string
*/
protected $name = null;
/**
* The name of the queue for this job
*
* @var string
*/
protected $queue = 'default';
/**
* The name of the queue connection to use
*
* @var string
*/
protected $connection = 'default';
/**
* Default wait time before dispatching the job, this is a strtotime compatible
* string. e.g '+5 minutes' or '+1 day' etc
*
* @example '+30 minutes'
* @var string
*/
protected $wait = null;
/**
* The default timeout in seconds. Set to 0 to disable.
*
* @var integer
*/
protected $timeout = 60;
/**
* Job identifier
*
* @var mixed
*/
protected $id = null;
/**
* Adapter id
*
* @var mixed
*/
protected $backendId = null;
/**
* These are the arguments that will be passed on to execute
*
* @var array
*/
protected $arguments = [];
/**
* Number of times this has been executed
*
* @var integer
*/
protected $attempts = 0;
/**
* The date this job was enqueued.
*
* @var string
*/
protected $enqueued = null;
/**
* If retry is called the info is stored here.
*
* @var array
*/
protected $retryOptions = null;
/**
* Date the job was serialized
*
* @var string|null
*/
protected $serialized = null;
/**
* Constructor
* @internal no dependency injection here because it would also have be serialized and there is the initialize
* issue as well, Only execute method
*/
public function __construct(array $options = [])
{
$options += ['wait' => $this->wait,'queue' => $this->queue];
$this->wait = $options['wait'];
$this->queue = $options['queue'];
$this->id = Security::uuid(['macAddress' => true]);
if ($this->name === null) {
list($namespace, $name) = namespaceSplit(get_class($this));
$this->name = substr($name, 0, -3);
}
}
/**
* Registers a callback to be called before a job is queued
*
* @param string $method
* @return void
*/
protected function beforeQueue(string $method): void
{
$this->registerCallback('beforeQueue', $method);
}
/**
* Registers a callback to be called before a job is queued
*
* @param string $method
* @return void
*/
protected function afterQueue(string $method): void
{
$this->registerCallback('afterQueue', $method);
}
/**
* Registers a callback to be called before a job is dispatch
*
* @param string $method
* @return void
*/
protected function beforeDispatch(string $method): void
{
$this->registerCallback('beforeDispatch', $method);
}
/**
* Registers a callback to be called before a job is dispatched
*
* @param string $method
* @return void
*/
protected function afterDispatch(string $method): void
{
$this->registerCallback('afterDispatch', $method);
}
/**
* Registers a callback for handling errors
*
* @param string $method
* @return void
*/
protected function onError(string $method): void
{
$this->registerCallback('onError', $method);
}
/**
* Registers a callback which run if successful
*
* @param string $method
* @return void
*/
protected function onSuccess(string $method): void
{
$this->registerCallback('onSuccess', $method);
}
/**
* Gets the id for this job
*
* @return string
*/
public function id(): string
{
return $this->id;
}
/**
* Sets/gets the id by backend if any
*
* @param int|string $id
* @return int|string|void
*/
public function backendId($id = null)
{
if ($id === null) {
return $this->backendId;
}
$this->backendId = $id;
}
/**
* Returns the connection for the Queue
*
* @return \Origin\Job\Engine\BaseEngine;
*/
public function connection(): BaseEngine
{
$connection = env('ORIGIN_ENV') === 'test' ? 'test' : $this->connection;
return Queue::connection($connection);
}
/**
* Dispatches the job to the queue with the given arguments.
*
* @return bool
*/
public function dispatch(): bool
{
$this->arguments = func_get_args();
$this->enqueued = date('Y-m-d H:i:s');
$this->dispatchCallback('beforeQueue', [$this->arguments]);
$result = $this->connection()->add($this, $this->wait ?: 'now');
$this->dispatchCallback('afterQueue', [$this->arguments]);
return $result;
}
/**
* Dispatches the job immediately with the given arguments.
*
* @return bool
*/
public function dispatchNow(): bool
{
$this->attempts ++;
$this->arguments = func_get_args(); // proces the arguments
try {
$this->executeHook('initialize');
$this->executeHook('startup');
if ($this->dispatchCallback('beforeDispatch', [$this->arguments])) {
$this->execute(...$this->arguments);
$this->dispatchCallback('afterDispatch', [$this->arguments]);
}
} catch (\Exception $e) {
Log::error($e->getMessage());
if ($this->enqueued) {
$this->connection()->fail($this);
}
$this->dispatchCallback('onError', [$e]);
if ($this->enqueued && $this->retryOptions) {
$this->connection()->retry($this, $this->retryOptions['limit'], $this->retryOptions['wait']);
}
$this->executeHook('shutdown');
return false;
}
if ($this->enqueued) {
$this->connection()->success($this);
}
$this->dispatchCallback('onSuccess', [$this->arguments]);
$this->executeHook('shutdown');
return true;
}
/**
* Retries a job
*
* @param array $options The following option keys are supported :
* - wait: a strtotime comptabile string defaults to 5 seconds. e.g. '+ 5 minutes'
* - limit: The maximum number of retries to do. Default:3
* @return bool
*/
public function retry(array $options = []): bool
{
$options += ['wait' => '+ 5 seconds','limit' => 3];
if ($this->attempts < $options['limit'] + 1) {
$this->retryOptions = $options;
return true;
}
return false;
}
/**
* Gets the number of attempts
*
* @return int
*/
public function attempts(): int
{
return $this->attempts;
}
/**
* Gets an array of the arguments that will be called with execute
*
* @return array
*/
public function arguments(): array
{
return $this->arguments;
}
/**
* Returns an array of data to be passed to connection
* to be serialized
*/
public function serialize(): array
{
return [
'className' => get_class($this),
'id' => $this->id,
'backendId' => $this->backendId,
'queue' => $this->queue,
'arguments' => serialize(new ArrayObject($this->arguments)),
'attempts' => $this->attempts,
'enqueued' => $this->enqueued,
'serialized' => date('Y-m-d H:i:s'),
];
}
/**
* Deserializes data from Job::serialize
*
* @param array $data
* @return void
*/
public function deserialize(array $data): void
{
$this->id = $data['id'];
$this->backendId = $data['backendId'];
$this->queue = $data['queue'];
$this->arguments = (array) unserialize($data['arguments']); # unserialize object and convert to []
$this->attempts = $data['attempts'];
$this->enqueued = $data['enqueued'];
$this->serialized = $data['serialized'];
}
/**
* Schedules a job using wait and returns this (chainable)
*
* @param string $strtotime a strtotime compatiable string e.g '+5 hours' ,'2020-01-01 10:40:00'
* @return \Origin\Job\Job
*/
public function schedule(string $strtotime): Job
{
$this->wait = $strtotime;
return $this;
}
/**
* Gets the queue name
*
* @return string
*/
public function queue(): string
{
return $this->queue;
}
/**
* Gets the timeout for this job
*
* @return integer
*/
public function timeout(): int
{
return $this->timeout;
}
/**
* Gets the display name for the job
*
* @return string
*/
public function name(): string
{
return $this->name;
}
}