I'm trying to run WordPress cron tasks right after scheduling some action events. Usually WordPress Cron at least takes one another page load to trigger scheduled tasks. I'm trying to do it right away. I've almost managed to do it as shown in the below code.
/* Plugin Name: Sample Cron Immediate Execution */
add_action('admin_menu', 'sample_cron_immediate_execution');
function sample_cron_immediate_execution() {
add_options_page(
'Sample Cron Immediate Execution',
'Sample Cron Immediate Execution',
'manage_options',
'sample_cron_immediate_execution',
'sample_cron_immediate_execution_admin');
}
function sample_cron_immediate_execution_admin() {
?>
<div class="wrap">
<?php
wp_schedule_single_event(time(), 'my_action1');
wp_schedule_single_event(time(), 'my_action2');
$cron_url = site_url( 'wp-cron.php?doing_wp_cron=0');
wp_remote_post( $cron_url, array( 'timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters( 'https_local_ssl_verify', true ) ) );
echo 'cron tasks should be executed by now.';
?>
</div>
<?php
}
add_action('my_action1', 'myeventfunc1');
function myeventfunc1() {
sleep(10); // assuming it's a heavy task
sample_log(date('l jS \of F Y h:i:s A'), __DIR__ . '/myevent1_log.html');
}
add_action('my_action2', 'myeventfunc2');
function myeventfunc2() {
sleep(10); // assuming it's a heavy task
sample_log(date('l jS \of F Y h:i:s A'), __DIR__ . '/myevent2_log.html');
}
function sample_log($time, $file) {
file_put_contents($file, $time . '<br />', FILE_APPEND);
}
The problem is that when one of the tasks is heavy, it seems WordPress does not complete all tasks in one call of wp-cron.php
. I'm guessing that the $_GET value, doing_wp_cron
, is something to do with it as I view the code of the core file,
One of the comments says
Use global $doing_wp_cron lock otherwise use the GET lock. If no lock, trying grabbing a new lock.
I don't fully understand what this is about. What I'd like to do is to execute multiple scheduled tasks right away without requiring to open another page regardless of the heaviness of the tasks.
Thanks for your information.