Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wp_schedule_event() in plugin not scheduling a cron event

I'm creating a WordPress plugin, when the plugin is activated I need a cron job to be scheduled to run every 5 minutes.

Here's my code;

// Register plugin activation hook
function my_plugin_activate() {
    if( !wp_next_scheduled( 'my_function_hook' ) ) {  
       wp_schedule_event( time(), '5', 'my_function_hook' );  
    }
}
register_activation_hook( __FILE__, 'my_plugin_activate' );

// Register plugin deactivation hook
function my_plugin_deactivate(){
    wp_clear_scheduled_hook('my_function_hook');
}
register_deactivation_hook(__FILE__,'my_plugin_deactivate');

// Function I want to run when cron event runs
function my_function(){
    //Function code
}
add_action( 'my_function_hook', 'my_function');

When I use this plugin https://wordpress.org/plugins/wp-crontrol/ to check the cron events, nothing has been added, I'm expecting a cron event to be added that runs 'my_function' at 5 minute intervals, I have no errors

like image 258
user3574766 Avatar asked Nov 12 '17 13:11

user3574766


1 Answers

See: wp_schedule_event()

Valid values for the recurrence are hourly, daily, and twicedaily. These can be extended using the ‘cron_schedules’ filter in wp_get_schedules().

So you just need to add a custom schedule that runs every 5 minutes.

<?php // Requires PHP 5.4+.

add_filter( 'cron_schedules', function ( $schedules ) {
    $schedules['every-5-minutes'] = array(
        'interval' => 5 * MINUTE_IN_SECONDS,
        'display'  => __( 'Every 5 minutes' )
    );
    return $schedules;
} );

if( ! wp_next_scheduled( 'my_function_hook' ) ) {  
    wp_schedule_event( time(), 'every-5-minutes', 'my_function_hook' );  
}
like image 138
jaswrks Avatar answered Sep 21 '22 08:09

jaswrks