wp_schedule_event() not working inside class activation function

php, wordpress

Solution

You need to define you action you registered with your scheduled event:

class My_Plugin{

function __construct($plugin_file){
    $this->plugin_file = $plugin_file;
}

function initialize(){
    register_activation_hook( $this->plugin_file, array( $this, 'register_activation_hook' ) );        
    add_action( 'this_is_my_action', array( $this, 'do_it' );
}

function register_activation_hook()
{
    if ( !wp_next_scheduled( 'this_is_my_action' ) ) {
        $this->log( 'Scheduling action.' );
        wp_schedule_event( time() + 10, 'hourly', 'this_is_my_action' );
    }
}

function this_is_my_action(){
//do
}

function log($message){
}

function do_it() {
    // This is your scheduled event
}

}

Problem

When I schedule an event at the top of the main plugin file (plugin.php) the cron gets added to wp_options `cron` option. `wp_schedule_event( time() + 10, 'hourly', 'this_is_my_action' );` This works fine, it adds the new cron. But, when I try to use the same function in my activation function within the plugin class, it doesn't work. Inside plugin.php i have: ``` $plugin = new My_Plugin(__FILE__); $plugin->initialize(); ``` Inside My_Plugin class I have: ``` class My_Plugin{ function __construct($plugin_file){ $this->plugin_file = $plugin_file; } function initialize(){ register_activation_hook( $this->plugin_file, array( $this, 'register_activation_hook' ) ); } function register_activation_hook() { $this->log( 'Scheduling action.' ); wp_schedule_event( time() + 10, 'hourly', 'this_is_my_action' ); } function log($message){ /*...*/ } } ``` The log gets written to when I activate the plugin, but the cron is not being added to wordpress database. Any ideas why?

Original source