'Wordpress wp_schedule_event not triggering at its custom interval
I am using an objected oriented design to build a plugin that will use a wp cron job to trigger a function every 10 seconds. However, I cannot get my wp cron job to trigger during this custom period (every 10 seconds).
My custom plugin class has a static activate function that successfully fires when the plugin is activated. This class is set out below.
class Datafetch {
public static function activate() {
update_option( 'rewrite_rules', '' );
require_once( DATAFETCH_PATH . 'schedule/class.datafetch-schedule.php' );
$Datafetch_Schedule = new Datafetch_Schedule();
$args = array();
add_filter( 'cron_schedules', $Datafetch_Schedule->set_seconds($args) );
if (!wp_next_scheduled('task_hook')) {
wp_schedule_event( time(), $args, array( 'Datafetch', 'task_hook' ) );
}
add_action( 'task_hook', $Datafetch_Schedule->begin_fetch_process(),10 );
}
The activate function instantiates the Datafetch_Schedule object. It then uses add_filter to call the method set_seconds, which sets the custom interval and then add_action to trigger the class's method begin_fetch_process. The Datafetch_Schedule class is set out below:
class Datafetch_Schedule{
public function __construct() {
}
public function begin_fetch_process() {
$args = [
'post_title' => 'Post every 10 seconds',
'post_content' => 'Test Post Content',
'post_status' => 'publish'
];
wp_insert_post($args);
}
function set_seconds( $schedules ) {
$schedules['ten_seconds'] = array(
'interval' => 10,
'display' => esc_html__( 'Every 10 Seconds' ), );
return $schedules;
}
}
The result is that one post with the title 'Post every 10 seconds' is posted at the time of the plugin's activation, but it does not post any more times. There is plenty of guidance on how to write a custom schedule, but not much of it centres around the use of classes. If any one can explain how I can successfully use the methods in the Datafetch class, from the main plugin class, to set the custom period and get my plugin to post every 10 seconds then I would be most grateful.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
