1
|
|
|
<?php |
2
|
|
|
namespace NirjharLo\WP_Plugin_Framework\Lib; |
3
|
|
|
|
4
|
|
|
if ( ! defined( 'ABSPATH' ) ) exit; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Add Cron schedules and cron task callback |
8
|
|
|
* |
9
|
|
|
* @author Nirjhar Lo |
10
|
|
|
* @package wp-plugin-framework |
11
|
|
|
*/ |
12
|
|
|
if ( ! class_exists( 'Cron' ) ) { |
13
|
|
|
|
14
|
|
|
final class Cron { |
15
|
|
|
|
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Add corn to wp scheduler |
19
|
|
|
* |
20
|
|
|
* @return Void |
21
|
|
|
*/ |
22
|
|
|
public function __construct() { |
23
|
|
|
|
24
|
|
|
//Add cron schedules |
25
|
|
|
add_filter('cron_schedules', array( $this, 'cron_schedules' ) ); |
|
|
|
|
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Set up the schedules |
31
|
|
|
* |
32
|
|
|
* @return Void |
33
|
|
|
*/ |
34
|
|
|
public function cron_schedules( $schedules ) { |
35
|
|
|
|
36
|
|
|
$prefix = 'prefix_'; // Avoid conflict with other crons. Example Reference: cron_30_mins |
37
|
|
|
|
38
|
|
|
// Example schedule options |
39
|
|
|
$schedule_options = array( |
40
|
|
|
'24_hrs' => array( |
41
|
|
|
'display' => '24 hours', |
42
|
|
|
'interval' => 86400 |
43
|
|
|
), |
44
|
|
|
'48_hrs' => array( |
45
|
|
|
'display' => '48 hours', |
46
|
|
|
'interval' => 172800 |
47
|
|
|
), |
48
|
|
|
'72_hrs' => array( |
49
|
|
|
'display' => '72 hours', |
50
|
|
|
'interval' => 259200 |
51
|
|
|
) |
52
|
|
|
); |
53
|
|
|
|
54
|
|
|
/* Add each custom schedule into the cron job system. */ |
55
|
|
|
foreach($schedule_options as $schedule_key => $schedule){ |
56
|
|
|
|
57
|
|
|
if(!isset($schedules[$prefix.$schedule_key])) { |
58
|
|
|
|
59
|
|
|
$schedules[$prefix.$schedule_key] = array( |
60
|
|
|
'interval' => $schedule['interval'], |
61
|
|
|
'display' => __( 'Every '.$schedule['display'] ) |
|
|
|
|
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $schedules; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Schedule the task based on added schedules |
72
|
|
|
* |
73
|
|
|
* @return Bool |
74
|
|
|
*/ |
75
|
|
|
public function schedule_task($task) { |
76
|
|
|
|
77
|
|
|
if( ! $task ) { |
78
|
|
|
return false; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
$required_keys = array( |
82
|
|
|
'timestamp', |
83
|
|
|
'recurrence', |
84
|
|
|
'hook' |
85
|
|
|
); |
86
|
|
|
$missing_keys = array(); |
87
|
|
|
foreach( $required_keys as $key ){ |
88
|
|
|
if( ! array_key_exists( $key, $task ) ) { |
89
|
|
|
$missing_keys[] = $key; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
if( ! empty( $missing_keys ) ){ |
94
|
|
|
return false; |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
if( wp_next_scheduled( $task['hook'] ) ){ |
|
|
|
|
98
|
|
|
wp_clear_scheduled_hook($task['hook']); |
|
|
|
|
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
wp_schedule_event($task['timestamp'], $task['recurrence'], $task['hook']); |
|
|
|
|
102
|
|
|
return true; |
103
|
|
|
} |
104
|
|
|
} |
105
|
|
|
} ?> |
|
|
|
|
106
|
|
|
|