Created
December 10, 2024 22:06
-
-
Save bhubbard/cdf2674de972cbdb75953286610541f3 to your computer and use it in GitHub Desktop.
This pattern ensures that a WP Cron job only runs during a specific time window (e.g., between midnight and 3 AM).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
How It Works: | |
• The cron job only runs if the current time is within the defined time window (midnight to 3 AM in this example). | |
• If it is outside the time window, the job is skipped. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Time Window Cron Execution Pattern | |
* | |
* Restricts a WP Cron job to run only within a specific time window. | |
*/ | |
// Define the allowed time window (e.g., 12 AM to 3 AM) | |
define( 'CRON_TIME_WINDOW_START', '00:00:00' ); | |
define( 'CRON_TIME_WINDOW_END', '03:00:00' ); | |
// Cron job callback | |
function my_cron_time_window_callback() { | |
// Your task here, e.g., send an email, process data, etc. | |
error_log( 'Cron job executed at ' . current_time( 'mysql' ) ); | |
} | |
// Check if current time is within the allowed time window | |
function my_cron_time_window_check() { | |
$current_time = current_time( 'H:i:s' ); | |
if ( $current_time >= CRON_TIME_WINDOW_START && $current_time <= CRON_TIME_WINDOW_END ) { | |
// Run the cron job | |
my_cron_time_window_callback(); | |
} else { | |
// Log that the cron job was skipped | |
error_log( 'Cron job skipped due to time window restriction.' ); | |
} | |
} | |
// Schedule the cron job | |
if ( ! wp_next_scheduled( 'my_cron_time_window_hook' ) ) { | |
wp_schedule_event( time(), 'hourly', 'my_cron_time_window_hook' ); | |
} | |
// Hook the time window check to WP Cron | |
add_action( 'my_cron_time_window_hook', 'my_cron_time_window_check' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment