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.