0

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.

Edit:

Crontrol displays this error:

There was a problem spawning a call to the WP-Cron system on your site.
This means WP-Cron events on your site may not work. The problem was: cURL
error 6: Could not resolve: test.localhost (Domain name not found)

Same error is displayed when deployed on a staging server.

6
  • How/when is MyPlugin instantiated? Commented Nov 22, 2019 at 8:33
  • try the plugin WP Crontrol it helps you to see what is set
    – Kaperto
    Commented Nov 22, 2019 at 8:41
  • @JacobPeattie it is instantiated in the same file, so basically on every pageload when active
    – jnaklaas
    Commented Nov 22, 2019 at 10:41
  • Keep in mind that WordPress 'cron' events don't fire at specific times, they only fire when a user visits your site for the first time after the scheduled time for an event. So if you schedule an event for 10:00, but don't get a visitor until 10:30, the event won't fire until 10:30. So if you're registering this hourly event on a private website, and then leave it alone for hours, the event's not going to fire because no one's visiting it to trigger the event. Commented Nov 22, 2019 at 10:44
  • @JacobPeattie Yes I'm aware, it's not that.
    – jnaklaas
    Commented Nov 22, 2019 at 10:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.