-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppCronManager.php
More file actions
94 lines (68 loc) · 2.29 KB
/
AppCronManager.php
File metadata and controls
94 lines (68 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
/**
* A simple WordPress cron job manager class
* @since: 1.0
* @author: Mahbub Alam Khan
* @created: 03.09.2024
* @updated: 03.09.2024
*/
class AppCronManager{
public $api_url;
public function __construct()
{
$limit = rand(2,5);
// Define the API URL
$this->api_url = "https://jsonplaceholder.typicode.com/users/1/todos?_limit={$limit}"; // Replace with your API endpoint
// Register a Custom Cron Schedule
add_filter('cron_schedules', [$this, 'custom_cron_schedules']);
// Schedule the Cron Job
add_action( 'wp', [$this,'custom_schedule_cron_job'] );
// Define the Cron Job Function
add_action( 'custom_cron_job_hook', [$this,'custom_cron_job_function']);
$this->readTransientData();
}
// Add a custom interval for 5 minutes
public function custom_cron_schedules($schedules):array {
$schedules['every_five_minutes'] = array(
'interval' => 300, // 300 seconds = 5 minutes
'display' => esc_html__( 'Every 5 Minutes' ),
);
return $schedules;
}
// Schedule the event if it's not already scheduled
public function custom_schedule_cron_job() {
// return 1;
if ( ! wp_next_scheduled( 'custom_cron_job_hook' ) ) {
wp_schedule_event( time(), 'every_five_minutes', 'custom_cron_job_hook' );
}
}
// Function to be executed by the cron job
public function custom_cron_job_function() {
$response = wp_remote_get( $this->api_url );
if ( is_wp_error( $response ) ) {
return; // Exit if there's an error
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
if ( ! empty( $data ) ) {
// Store data in a transient for 5 minutes (300 seconds)
set_transient( 'custom_api_data', $data, 300 );
}
}
public function readTransientData(){
// Retrieve data from the transient
$api_data = get_transient( 'custom_api_data' );
if ( false !== $api_data ) {
// Data is available and valid, do something with it
// Example: Display data
echo '<pre>';
print_r( $api_data );
echo '</pre>';
} else {
// Data is not available or expired
echo 'No data available or transient expired.';
}
}
}
// Initialize Class.
new AppCronManager();