First of its important where this code is in, is it in your functions.php for your theme? Or is it a custom plugin your developing?
Through my experience its both easier to debug and activate cron through a custom plugin, using activation hooks to activate and deactivate events. I have had hard times activating cron events through functions php before, I prefer activating these events through custom plugins.
I would start with a plugin structure like this:
- /my-cron-plugin
- /my-cron-plugin/index.php
- /my-cron-plugin/my-cron-plugin.php
index.php contents:
<?php // silence is golden
my-cron-plugin.php contents:
<?php
/**
* Plugin name: My Custom Cron Plugin
* Description: Simple WP cron plugin boilerplate.
* Author: Your name
* Version: 0.1
*/
// Security reasons...
if( !function_exists( 'add_action' ) ){
die('...');
}
// The activation hook
function isa_activation(){
if( !wp_next_scheduled( 'isa_add_every_three_minutes_event' ) ){
wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes_event' );
}
}
register_activation_hook( __FILE__, 'isa_activation' );
// The deactivation hook
function isa_deactivation(){
if( wp_next_scheduled( 'isa_add_every_three_minutes_event' ) ){
wp_clear_scheduled_hook( 'isa_add_every_three_minutes_event' );
}
}
register_deactivation_hook( __FILE__, 'isa_deactivation' );
// The schedule filter hook
function isa_add_every_three_minutes( $schedules ) {
$schedules['every_three_minutes'] = array(
'interval' => 180,
'display' => __( 'Every 3 Minutes', 'textdomain' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
// The WP Cron event callback function
function isa_every_three_minutes_event_func() {
// do something
}
add_action( 'isa_add_every_three_minutes_event', 'isa_every_three_minutes_event_func' );
After having setup this plugin, the event should be activated upon plugin activation. To test if its working use this plugin: https://wordpress.org/plugins/wp-crontrol/
One other good resource to understand how WP cron work is: https://developer.wordpress.org/plugins/cron/