Actions
6 months ago
ActionScheduler.php
2 months ago
RemoteExecutorHandler.php
2 years ago
index.php
3 years ago
RemoteExecutorHandler.php
69 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Cron\ActionScheduler; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Util\Helpers; |
| 9 | use MailPoet\WP\Functions as WPFunctions; |
| 10 | |
| 11 | class RemoteExecutorHandler { |
| 12 | const AJAX_ACTION_NAME = 'mailpoet-cron-action-scheduler-run'; |
| 13 | |
| 14 | /** @var WPFunctions */ |
| 15 | private $wp; |
| 16 | |
| 17 | public function __construct( |
| 18 | WPFunctions $wp |
| 19 | ) { |
| 20 | $this->wp = $wp; |
| 21 | } |
| 22 | |
| 23 | public function init(): void { |
| 24 | $this->wp->addAction('wp_ajax_nopriv_' . self::AJAX_ACTION_NAME, [$this, 'runActionScheduler'], 0); |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Attempts to spawn Action Scheduler runner via ajax request |
| 29 | * @see https://actionscheduler.org/perf/#increasing-initialisation-rate-of-runners |
| 30 | */ |
| 31 | public function triggerExecutor(): void { |
| 32 | $this->wp->addFilter('https_local_ssl_verify', '__return_false', 100); |
| 33 | $this->wp->wpRemotePost($this->wp->adminUrl('admin-ajax.php'), [ |
| 34 | 'method' => 'POST', |
| 35 | 'timeout' => 5, |
| 36 | 'redirection' => 5, |
| 37 | 'httpversion' => '1.0', |
| 38 | 'blocking' => false, |
| 39 | 'headers' => [], |
| 40 | 'body' => [ |
| 41 | 'action' => self::AJAX_ACTION_NAME, |
| 42 | ], |
| 43 | 'cookies' => [], |
| 44 | ]); |
| 45 | } |
| 46 | |
| 47 | public function runActionScheduler(): void { |
| 48 | try { |
| 49 | $this->wp->addFilter('action_scheduler_queue_runner_concurrent_batches', [$this, 'ensureConcurrency']); |
| 50 | \ActionScheduler_QueueRunner::instance()->run(); |
| 51 | wp_die(); |
| 52 | } catch (\Exception $e) { |
| 53 | $mySqlGoneAwayMessage = Helpers::mySqlGoneAwayExceptionHandler($e); |
| 54 | if ($mySqlGoneAwayMessage) { |
| 55 | throw new \Exception($mySqlGoneAwayMessage, 0, $e); |
| 56 | } |
| 57 | throw $e; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * When triggering new runner at the end of a runner execution |
| 63 | * we need to make sure the concurrency allows more one runner. |
| 64 | */ |
| 65 | public function ensureConcurrency(int $concurrency): int { |
| 66 | return ($concurrency) < 2 ? 2 : $concurrency; |
| 67 | } |
| 68 | } |
| 69 |