PluginProbe
ووسلام – همگام سازی ووکامرس و باسلام / 1.9.0
ووسلام – همگام سازی ووکامرس و باسلام v1.9.0
1.10.19 1.10.20 1.10.18 1.10.17 1.10.15 1.10.14 1.10.13 1.10.12 1.10.10 1.10.9 1.10.8 1.10.7 1.10.6 1.10.5 1.10.4 1.10.3 1.10.2 1.10.1 1.10.0 1.9.2 1.9.1 1.9.0 1.8.8 1.8.5 1.8.6 All 53 releases
sync-basalam / JobsRunner.php

JobsRunner.php in ووسلام – همگام سازی ووکامرس و باسلام 1.9.0, at JobsRunner.php

99 lines 2.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 const GLOBAL_RUNNER_LAST_RUN_OPTION = 'sync_basalam_jobs_runner_last_run';
13
14 private $jobExecutor;
15 private $jobManager;
16 private $discountScheduler;
17 private $CheckHttpBlockService;
18
19 public function __construct(
20 $jobManager,
21 $jobExecutor,
22 $discountScheduler,
23 $CheckHttpBlockService
24 ) {
25 add_action('init', [$this, 'checkAndRunJobs']);
26 $this->jobManager = $jobManager;
27 $this->jobExecutor = $jobExecutor;
28 $this->discountScheduler = $discountScheduler;
29 $this->CheckHttpBlockService = $CheckHttpBlockService;
30 }
31
32 public function checkAndRunJobs(): void
33 {
34 if ($this->CheckHttpBlockService->SyncBasalamHttpBlock()) return;
35 if (!$this->jobExecutor->acquireGlobalJobsLock(0)) return;
36
37 try {
38 $this->runEligibleJobs();
39 } finally {
40 $this->jobExecutor->releaseGlobalJobsLock();
41 }
42 }
43
44 private function runEligibleJobs(): void
45 {
46 $this->jobManager->ConvertStaleProcessingJobs(120);
47 $this->discountScheduler->process();
48
49 $circuitBreaker = new CircuitBreaker();
50 if ($circuitBreaker->getState() === CircuitBreaker::STATE_OPEN) {
51 return;
52 }
53
54 if ($this->jobManager->hasAnyProcessingJob()) {
55 return;
56 }
57
58 $tasksPerMinute = max(1, intval(Settings::getEffectiveTasksPerMinute()));
59 $thresholdSeconds = 60.0 / $tasksPerMinute;
60 $lastRun = floatval(get_option(self::GLOBAL_RUNNER_LAST_RUN_OPTION, 0));
61 $now = microtime(true);
62
63 if (($now - $lastRun) < $thresholdSeconds) {
64 return;
65 }
66
67 $sortedJobTypes = $this->jobExecutor->getSortedJobTypes();
68
69 foreach ($sortedJobTypes as $jobType => $jobExecutor) {
70 if (!$this->jobExecutor->canRun($jobType)) {
71 continue;
72 }
73
74 $job = $this->jobManager->getNextEligibleJob($jobType);
75 $processingJob = $this->jobManager->getJob(['job_type' => $jobType, 'status' => 'processing']);
76
77 if (!$job || $processingJob) {
78 continue;
79 }
80
81 update_option(self::GLOBAL_RUNNER_LAST_RUN_OPTION, microtime(true), false);
82
83 $this->jobManager->updateJob(
84 ['status' => 'processing', 'started_at' => time()],
85 ['id' => $job->id]
86 );
87
88 $this->executeJob($job);
89 break;
90 }
91 }
92
93 private function executeJob(object $job): void
94 {
95 $jobType = $job->job_type;
96 $this->jobExecutor->execute($jobType, $job);
97 }
98 }
99