| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Queue; |
| 4 |
|
| 5 |
defined('ABSPATH') || exit; |
| 6 |
class QueueManager |
| 7 |
{ |
| 8 |
private const GROUP_NAME = 'sync-basalam'; |
| 9 |
|
| 10 |
public $taskName; |
| 11 |
|
| 12 |
public function __construct($taskName) |
| 13 |
{ |
| 14 |
$this->taskName = $taskName; |
| 15 |
} |
| 16 |
|
| 17 |
public function scheduleSingleTask($args = [], $delay = 0) |
| 18 |
{ |
| 19 |
$timestamp = time() + $delay; |
| 20 |
|
| 21 |
$this->setLastRunTimestamp($timestamp); |
| 22 |
|
| 23 |
return \WC()->queue()->schedule_single( |
| 24 |
$timestamp, |
| 25 |
$this->taskName, |
| 26 |
[$args], |
| 27 |
self::GROUP_NAME |
| 28 |
); |
| 29 |
} |
| 30 |
|
| 31 |
public function scheduleRecurringTask($intervalInSeconds, $args = []) |
| 32 |
{ |
| 33 |
if (self::hasPendingTasks($this->taskName)) return false; |
| 34 |
|
| 35 |
$startTimestamp = time(); |
| 36 |
|
| 37 |
$this->setLastRunTimestamp($startTimestamp); |
| 38 |
|
| 39 |
return \WC()->queue()->schedule_recurring( |
| 40 |
$startTimestamp, |
| 41 |
$intervalInSeconds, |
| 42 |
$this->taskName, |
| 43 |
[$args], |
| 44 |
self::GROUP_NAME |
| 45 |
); |
| 46 |
} |
| 47 |
|
| 48 |
protected function setLastRunTimestamp($timestamp) |
| 49 |
{ |
| 50 |
return update_option($this->taskName . '_last_run', $timestamp); |
| 51 |
} |
| 52 |
|
| 53 |
public static function hasPendingTasks($taskName) |
| 54 |
{ |
| 55 |
$pendingTasks = \WC()->queue()->search([ |
| 56 |
'hook' => $taskName, |
| 57 |
'status' => 'pending', |
| 58 |
]); |
| 59 |
|
| 60 |
return !empty($pendingTasks); |
| 61 |
} |
| 62 |
|
| 63 |
public static function cancelAllTasksGroup($taskName) |
| 64 |
{ |
| 65 |
\WC()->queue()->cancel_all($taskName); |
| 66 |
|
| 67 |
delete_option($taskName . '_last_run'); |
| 68 |
} |
| 69 |
|
| 70 |
public static function countOfPendingTasks($taskName) |
| 71 |
{ |
| 72 |
$pendingTasks = \WC()->queue()->search([ |
| 73 |
'hook' => $taskName, |
| 74 |
'status' => 'pending', |
| 75 |
'per_page' => 5000, |
| 76 |
]); |
| 77 |
|
| 78 |
return count($pendingTasks); |
| 79 |
} |
| 80 |
} |
| 81 |
|