PluginProbe
Solid Performance – Your No-Code Caching, Performance, & Page Speed Solution / trunk
Solid Performance – Your No-Code Caching, Performance, & Page Speed Solution vtrunk
2.0.1 trunk 1.0.0 1.1.0 1.2.0 1.3.0 1.3.1 1.3.2 1.3.3 1.4.0 1.4.1 1.4.2 1.5.0 1.6.0 1.6.1 1.7.0 1.7.1 1.8.0 1.9.0 2.0.0
solid-performance / src / Performance / Cron / Scheduler.php

Scheduler.php in Solid Performance – Your No-Code Caching, Performance, & Page Speed Solution trunk, at src/Performance/Cron/Scheduler.php

95 lines 1.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * The cron task scheduler.
4 *
5 * @package SolidWP\Performance
6 */
7
8 declare( strict_types=1 );
9
10 namespace SolidWP\Performance\Cron;
11
12 use SolidWP\Performance\Psr\Log\LoggerInterface;
13 use WP_Error;
14
15 /**
16 * The cron task scheduler.
17 *
18 * @package SolidWP\Performance
19 */
20 final class Scheduler {
21
22 /**
23 * @var Registry
24 */
25 private Registry $registry;
26
27 /**
28 * @var LoggerInterface
29 */
30 private LoggerInterface $logger;
31
32 /**
33 * @param Registry $registry The task registry.
34 * @param LoggerInterface $logger The logger.
35 */
36 public function __construct( Registry $registry, LoggerInterface $logger ) {
37 $this->registry = $registry;
38 $this->logger = $logger;
39 }
40
41 /**
42 * Schedule all tasks with WordPress.
43 *
44 * @return void
45 */
46 public function enable_tasks(): void {
47 foreach ( $this->registry->all() as $task ) {
48 if ( ! wp_next_scheduled( $task->hook() ) ) {
49 wp_schedule_event( time(), $task->recurrence(), $task->hook() );
50 }
51 }
52 }
53
54 /**
55 * Clear all registered tasks.
56 *
57 * @return void
58 */
59 public function disable_tasks(): void {
60 foreach ( $this->registry->all() as $task ) {
61 $result = wp_clear_scheduled_hook( $task->hook(), [], true );
62
63 if ( $result instanceof WP_Error ) {
64 $this->logger->error(
65 'Error clearing scheduled hook: {message}',
66 [
67 'message' => $result->get_error_message(),
68 'wp_error' => $result,
69 ]
70 );
71 }
72 }
73 }
74
75 /**
76 * Register all task hooks from the registry.
77 *
78 * @return void
79 */
80 public function register_task_hooks(): void {
81 foreach ( $this->registry->all() as $task ) {
82 if ( has_action( $task->hook() ) ) {
83 continue;
84 }
85
86 add_action(
87 $task->hook(),
88 static fn() => $task->run(),
89 10,
90 0
91 );
92 }
93 }
94 }
95