| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Hooks\Scheduler; |
| 4 |
|
| 5 |
use FluentCart\App\App; |
| 6 |
use FluentCart\App\Helpers\Status; |
| 7 |
use FluentCart\App\Models\ProductMeta; |
| 8 |
use FluentCart\App\Models\ScheduledAction; |
| 9 |
use FluentCart\App\Modules\Integrations\GlobalNotificationHandler; |
| 10 |
use FluentCart\App\Services\DateTime\DateTime; |
| 11 |
use FluentCart\Framework\Support\Arr; |
| 12 |
|
| 13 |
class JobRunner |
| 14 |
{ |
| 15 |
protected static $instance = null; |
| 16 |
protected $actionIds = []; |
| 17 |
protected $actions = []; |
| 18 |
protected $startedAt; |
| 19 |
|
| 20 |
public function __construct() |
| 21 |
{ |
| 22 |
$this->startedAt = DateTime::gmtNow(); |
| 23 |
} |
| 24 |
|
| 25 |
public function async($hook, $scheduleActionData) |
| 26 |
{ |
| 27 |
$data = array_merge([ |
| 28 |
'status' => 'pending' |
| 29 |
], $scheduleActionData); |
| 30 |
$queueId = $this->addQueue($data); |
| 31 |
|
| 32 |
if (function_exists('as_enqueue_async_action')) { |
| 33 |
as_enqueue_async_action($hook, [ 'scheduled_action_id' => $queueId ], 'fluent-cart'); |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
public function start($filters = []): void |
| 38 |
{ |
| 39 |
$jobs = ScheduledAction::query()->where('status', 'pending') |
| 40 |
->where('retry_count', '<', 5) |
| 41 |
->where('scheduled_at', '<=', $this->startedAt) |
| 42 |
->where($filters) |
| 43 |
->orderBy('scheduled_at', 'asc') |
| 44 |
->limit(100) |
| 45 |
->get(); |
| 46 |
|
| 47 |
foreach ($jobs as $job) { |
| 48 |
$this->runScheduler($job); |
| 49 |
$timeDiff = DateTime::gmtNow()->getTimestamp() - $this->startedAt->getTimestamp(); |
| 50 |
if ($timeDiff > 30) { |
| 51 |
// If we have been running for more than 30 seconds, stop processing |
| 52 |
break; |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
public function runScheduler(ScheduledAction $job): void |
| 58 |
{ |
| 59 |
if ($job->group === 'integration') { |
| 60 |
(new GlobalNotificationHandler())->processIntegrationAction($job->id); |
| 61 |
$job->update(['status' => Status::SCHEDULE_COMPLETED]); |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
public function addQueue(array $data) |
| 66 |
{ |
| 67 |
if (!isset($data['status'])) { |
| 68 |
$data['status'] = Status::SCHEDULE_PENDING; |
| 69 |
} |
| 70 |
|
| 71 |
if (!isset($data['retry_count'])) { |
| 72 |
$data['retry_count'] = 0; |
| 73 |
} |
| 74 |
|
| 75 |
$data['created_at'] = current_time('mysql'); |
| 76 |
return ScheduledAction::query()->insertGetId($data); |
| 77 |
} |
| 78 |
} |
| 79 |
|