DaemonTrigger.php
74 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Cron\ActionScheduler\Actions; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Cron\ActionScheduler\ActionScheduler; |
| 9 | use MailPoet\Cron\ActionScheduler\RemoteExecutorHandler; |
| 10 | use MailPoet\Cron\DaemonActionSchedulerRunner; |
| 11 | use MailPoet\Cron\Triggers\WordPress; |
| 12 | use MailPoet\WP\Functions as WPFunctions; |
| 13 | |
| 14 | class DaemonTrigger { |
| 15 | const NAME = 'mailpoet/cron/daemon-trigger'; |
| 16 | const TRIGGER_RUN_INTERVAL = 120; // 2 minutes |
| 17 | |
| 18 | /** @var WPFunctions */ |
| 19 | private $wp; |
| 20 | |
| 21 | /** @var WordPress */ |
| 22 | private $wordpressTrigger; |
| 23 | |
| 24 | /** @var RemoteExecutorHandler */ |
| 25 | private $remoteExecutorHandler; |
| 26 | |
| 27 | /** @var ActionScheduler */ |
| 28 | private $actionScheduler; |
| 29 | |
| 30 | public function __construct( |
| 31 | WPFunctions $wp, |
| 32 | WordPress $wordpressTrigger, |
| 33 | RemoteExecutorHandler $remoteExecutorHandler, |
| 34 | ActionScheduler $actionScheduler |
| 35 | ) { |
| 36 | $this->wp = $wp; |
| 37 | $this->wordpressTrigger = $wordpressTrigger; |
| 38 | $this->remoteExecutorHandler = $remoteExecutorHandler; |
| 39 | $this->actionScheduler = $actionScheduler; |
| 40 | } |
| 41 | |
| 42 | public function init() { |
| 43 | $this->wp->addAction(self::NAME, [$this, 'process']); |
| 44 | |
| 45 | if (!$this->actionScheduler->hasScheduledAction(self::NAME)) { |
| 46 | // Don't schedule if plugin is being deactivated (prevents race condition with parallel requests) |
| 47 | // Note: We check the option directly instead of using DaemonActionSchedulerRunner::isDeactivating() |
| 48 | // to avoid a circular dependency (DaemonActionSchedulerRunner depends on DaemonTrigger) |
| 49 | if ($this->wp->getOption(DaemonActionSchedulerRunner::DEACTIVATION_FLAG_OPTION, false)) { |
| 50 | return; |
| 51 | } |
| 52 | $this->actionScheduler->scheduleRecurringAction($this->wp->currentTime('timestamp', true), self::TRIGGER_RUN_INTERVAL, self::NAME); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * It checks if there are scheduled tasks to execute. |
| 58 | * In case there are tasks to do, it schedules a daemon-run action. |
| 59 | */ |
| 60 | public function process(): void { |
| 61 | $hasJobsToDo = $this->wordpressTrigger->checkExecutionRequirements(); |
| 62 | if (!$hasJobsToDo) { |
| 63 | $this->actionScheduler->unscheduleAction(DaemonRun::NAME); |
| 64 | return; |
| 65 | } |
| 66 | if ($this->actionScheduler->hasScheduledAction(DaemonRun::NAME)) { |
| 67 | return; |
| 68 | } |
| 69 | // Schedule immediate action for execution of the daemon |
| 70 | $this->actionScheduler->scheduleImmediateSingleAction(DaemonRun::NAME); |
| 71 | $this->remoteExecutorHandler->triggerExecutor(); |
| 72 | } |
| 73 | } |
| 74 |