I created a plugin with a cron to update all posts of a certain type every 5 minutes. I installed WP Crontrol to check if the cron is registered correctly and everything seems to be okay.
This is how I registered my cron:
function custom_cron_interval( $schedules ) {
$schedules['fiveminutes'] = array(
'interval' => 300,
'display' => __('Every five minutes')
);
return $schedules;
}
add_filter( 'cron_schedules', 'custom_cron_interval' );
if ( ! wp_next_scheduled( 'recalculate_all_scores' ) ) {
wp_schedule_event(time(), 'fiveminutes', 'recalculate_all_scores');
}
It is registered correctly but when the function executes, nothing happens. For testing purposes I hooked the function to the save_post action. Everything works fine this way. But when the scheduled task is called, it won’t execute.
Here is the code of the function
function recalculate_all_scores() {
global $wpdb;
$customers = $wpdb->get_results("SELECT * FROM wp_posts
WHERE post_type="customer"
AND post_status="publish";");
foreach ($customers as $customer){
set_score($customer);
}
}
function set_score($customer){
$acf_key = "score";
$score = rand(0,50);
update_field( $acf_key, $score, $customer->ID );
}
I also added the following lines to my wp-config.php:
define('ALTERNATE_WP_CRON', true);
define('DISABLE_WP_CRON', false);
Any idea what is stopping the function from executing?
EDIT
- I’m aware that the wp_cron system is not a real cron and that it relies on site visits.
- If I execute the function manually it takes about 15 seconds so the PHP execution time limit should not be a problem.
2 Answers
I was having the same issue recently, until I followed an example from the WordPress Codex which suggests using action hooks to run the function.
I think if you add the following…
add_action( 'recalculate_all_scores_hook', 'recalculate_all_scores' );
…and amend the wp_schedule_event function to use the action hook name rather than the function directly…
wp_schedule_event( time(), 'fiveminutes', 'recalculate_all_scores_hook' );
…you might be in business.
Good luck!