wp_schedule_event doesn’t work

Question

I wrote a plugin which now needs a daily scheduled event. For testing purposes I’ve written an hourly scheduled event.

class MyPlugin {

  public function __construct() {

    add_action('hourly_cron_job', function(){
      error_log('hourly_cron_job action called');
    });

    if ( is_admin() ) {
      register_activation_hook( __FILE__, [ $this, 'scheduleCrons' ] );
      register_deactivation_hook( __FILE__, [ $this, 'unscheduleCrons' ]);
    }
  }

  public function scheduleCrons()
  {
    error_log('scheduleCrons called');
    if (! wp_next_scheduled ( 'hourly_cron_job' )) {
         wp_schedule_event(time()+30, 'hourly', 'hourly_cron_job' );
    }
  }

  public function unscheduleCrons()
  {
    error_log('unscheduleCrons called');
    wp_clear_scheduled_hook( 'hourly_cron_job' );
  }
}

My error log shows scheduleCrons called upon plugin activation. But the action hook never seems to be called. What’s going on?

I’ve tried to define('ALTERNATE_WP_CRON', true); but it doesn’t make any difference.
Calling wp_next_scheduled ( 'hourly_cron_job' ) returns the timestamp as expected.
Calling wp_get_schedule( 'hourly_cron_job' ); returns hourly as expected.

0
JKL 2 years 2019-11-22T02:12:39-05:00 0 Answers 158 views 0

Leave an answer

Browse
Browse