Skip to content

Instantly share code, notes, and snippets.

@bhubbard
Created December 10, 2024 22:06
Show Gist options
  • Save bhubbard/471c67497014970135a8aae6d8312893 to your computer and use it in GitHub Desktop.
Save bhubbard/471c67497014970135a8aae6d8312893 to your computer and use it in GitHub Desktop.
This pattern limits the execution frequency of WP Cron jobs, ensuring that they do not run more frequently than a set threshold, even if the scheduled time has passed.
How It Works:
• The cron job runs only if the time since the last run is greater than or equal to the defined throttle interval (in this case, 1 hour).
• It checks this condition before executing the task, ensuring that the job isn’t triggered too frequently.
<?php
/**
* Cron Job Throttling Pattern
*
* Limits the frequency of a WP Cron job to avoid overwhelming the server.
*/
// Define the interval between allowed cron executions (in seconds)
define( 'MY_CRON_JOB_THROTTLE_INTERVAL', 3600 ); // 1 hour
// Cron job callback
function my_cron_job_callback() {
// Your task here, e.g., send an email, process data, etc.
error_log( 'Cron job executed at ' . current_time( 'mysql' ) );
}
// Check if the cron job is allowed to run based on the throttle interval
function my_cron_job_throttled_check() {
$last_run = get_option( 'my_cron_job_last_run', 0 );
$current_time = time();
if ( ( $current_time - $last_run ) >= MY_CRON_JOB_THROTTLE_INTERVAL ) {
// Run the cron job
my_cron_job_callback();
// Update the last run time
update_option( 'my_cron_job_last_run', $current_time );
}
}
// Schedule the cron job
if ( ! wp_next_scheduled( 'my_cron_job_hook' ) ) {
wp_schedule_event( time(), 'hourly', 'my_cron_job_hook' );
}
// Hook the throttled cron check to WP Cron
add_action( 'my_cron_job_hook', 'my_cron_job_throttled_check' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment