Hourly Event Scheduling WordPress
January 24, 2025 ยท AI Conversations
—
### 1. Register the Hourly Schedule Event
Add the following code to your theme's `functions.php` file or a custom plugin:
// Register custom cron schedule if not already registered
function custom_add_hourly_schedule( $schedules ) {
if ( ! isset( $schedules['hourly'] ) ) {
$schedules['hourly'] = array(
'interval' => 3600, // Interval in seconds
'display' => __( 'Once Hourly' ),
);
}
return $schedules;
}
add_filter( 'cron_schedules', 'custom_add_hourly_schedule' );
// Schedule the event
function custom_schedule_hourly_event() {
if ( ! wp_next_scheduled( 'custom_hourly_event' ) ) {
wp_schedule_event( time(), 'hourly', 'custom_hourly_event' );
}
}
add_action( 'wp', 'custom_schedule_hourly_event' );
// Hook into the event
add_action( 'custom_hourly_event', 'custom_execute_hourly_task' );
// Define the task to run
function custom_execute_hourly_task() {
// Your custom task here
error_log( 'Hourly task executed at ' . current_time( 'mysql' ) );
}
—
### 2. Unschedule the Event (Optional)
If you need to remove the event, you can do so with `wp_clear_scheduled_hook()`:
function custom_remove_hourly_event() {
$timestamp = wp_next_scheduled( 'custom_hourly_event' );
if ( $timestamp ) {
wp_unschedule_event( $timestamp, 'custom_hourly_event' );
}
}
register_deactivation_hook( __FILE__, 'custom_remove_hourly_event' );
—
### Explanation
1. **`cron_schedules` Filter**:
Adds the hourly schedule if it doesn't exist in WordPress' default intervals.
2. **`wp_schedule_event()`**:
Ensures the event is scheduled only once. If it already exists, it won't create a duplicate.
3. **Hook**:
Binds the `custom_hourly_event` to a function where your custom logic resides.
4. **Deactivation Cleanup**:
Ensures the scheduled event is unscheduled when the plugin or theme is deactivated.
—
### 3. Verify Cron is Working
Use plugins like **WP Crontrol** to manage and debug WordPress cron jobs. You can see if your event is scheduled and test its execution.
Let me know if you encounter any issues!