Scheduling a task using class methods

I need to implement a scheduled task in my plugin, and I tried to follow the examples in the documentation, passing one of class methods as the target. I installed Cron Manager plugin, and I see that my hook has been scheduled, but the first schedule is a few seconds in the past. I guess that’s because WP sets the very first schedule to “now”, which, supposedly, should call the hook straight away.

The issue is that the method I attached to the hook is not called, and Cron Manager displays “seconds left: -X” (where X is the amount of seconds passed from the moment I scheduled the task).

I will skip the wp_schedule stuff as I know that it works (the hook is in the scheduled list, although with a timestamp in the past), so here’s the relevant code:

// Cron hook is called myclass_cron
class MyClass {
    public function __construct() {
        add_action('init', array($this, 'wordpress_loaded'));
    }

    public function wordpress_loaded() {
        add_action('myclass_cron', array($this, 'cron_tasks'));
    }

    public function cron_tasks() {
        // Cron stuff. I tried adding a "sleep()" command to see if page load was slower, but it clearly doesn't go through this method
    }
}

If I add a do_action('myclass_cron'), cron_tasks() runs as expected. I was wondering if I was calling add_action() too late (i.e. when WP is loaded), but I tried to move it to the Class Constructor, and the issue persisted.

Thanks in advance for the answers.

1 Answer
1

I actually found out that the Cron works, just not as I expected. I refreshed the pages and called wp-cron.php (using wget) a couple of times, and I kept seeing my cron task schedule with “-X seconds“. Then I stopped for a minute or two, and refreshed the frontend page of the site, and my Cron task got called.

When it was time for the second scheduled execution, one hour later, I repeated the test. Task was due in a couple of seconds, so I waited about 10 seconds an loaded a random page: nothing happened. I waited another half a minute or so, loaded again a random page, and the task got called.

It seems that WordPress has a “relaxed” way of calling Cron jobs, which I don’t fully understand yet. Anyway, my approach was correct, my expectations were not. 🙂

Leave a Comment