| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam; |
| 4 |
|
| 5 |
use SyncBasalam\Admin\Settings; |
| 6 |
use SyncBasalam\Services\Api\CircuitBreaker; |
| 7 |
|
| 8 |
defined('ABSPATH') || exit; |
| 9 |
|
| 10 |
class JobsRunner |
| 11 |
{ |
| 12 |
private $jobExecutor; |
| 13 |
private $jobManager; |
| 14 |
private $discountScheduler; |
| 15 |
private $CheckHttpBlockService; |
| 16 |
|
| 17 |
public function __construct( |
| 18 |
$jobManager, |
| 19 |
$jobExecutor, |
| 20 |
$discountScheduler, |
| 21 |
$CheckHttpBlockService |
| 22 |
) |
| 23 |
{ |
| 24 |
add_action('init', [$this, 'checkAndRunJobs']); |
| 25 |
$this->jobManager = $jobManager; |
| 26 |
$this->jobExecutor = $jobExecutor; |
| 27 |
$this->discountScheduler = $discountScheduler; |
| 28 |
$this->CheckHttpBlockService = $CheckHttpBlockService; |
| 29 |
} |
| 30 |
|
| 31 |
public function checkAndRunJobs(): void |
| 32 |
{ |
| 33 |
if($this->CheckHttpBlockService->SyncBasalamHttpBlock()) return; |
| 34 |
$this->jobManager->ConvertStaleProcessingJobs(120); |
| 35 |
$this->discountScheduler->process(); |
| 36 |
|
| 37 |
$circuitBreaker = new CircuitBreaker(); |
| 38 |
if ($circuitBreaker->getState() === CircuitBreaker::STATE_OPEN) { |
| 39 |
return; |
| 40 |
} |
| 41 |
|
| 42 |
$tasksPerMinute = max(1, intval(Settings::getEffectiveTasksPerMinute())); |
| 43 |
$thresholdSeconds = 60.0 / $tasksPerMinute; |
| 44 |
|
| 45 |
$sortedJobTypes = $this->jobExecutor->getSortedJobTypes(); |
| 46 |
|
| 47 |
foreach ($sortedJobTypes as $jobType => $jobExecutor) { |
| 48 |
if (!$this->jobExecutor->acquireLock($jobType, 0)) continue; |
| 49 |
try { |
| 50 |
$lastRun = floatval(get_option($jobType . '_last_run', 0)); |
| 51 |
$now = microtime(true); |
| 52 |
|
| 53 |
if (($now - $lastRun) >= $thresholdSeconds) { |
| 54 |
if (!$this->jobExecutor->canRun($jobType)) { |
| 55 |
continue; |
| 56 |
} |
| 57 |
|
| 58 |
$job = $this->jobManager->getNextEligibleJob($jobType); |
| 59 |
$processingJob = $this->jobManager->getJob(['job_type' => $jobType, 'status' => 'processing']); |
| 60 |
|
| 61 |
if ($job && !$processingJob) { |
| 62 |
update_option($jobType . '_last_run', microtime(true), false); |
| 63 |
|
| 64 |
$this->jobManager->updateJob( |
| 65 |
['status' => 'processing', 'started_at' => time()], |
| 66 |
['id' => $job->id] |
| 67 |
); |
| 68 |
|
| 69 |
$this->jobExecutor->releaseLock($jobType); |
| 70 |
|
| 71 |
$this->executeJob($job); |
| 72 |
|
| 73 |
break; |
| 74 |
} |
| 75 |
} |
| 76 |
} finally { |
| 77 |
$this->jobExecutor->releaseLock($jobType); |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
private function executeJob(object $job): void |
| 83 |
{ |
| 84 |
$jobType = $job->job_type; |
| 85 |
$this->jobExecutor->execute($jobType, $job); |
| 86 |
} |
| 87 |
} |
| 88 |
|