I have noticed this pattern in some plugins lately:
<?php
function MY_CRON(){
wp_schedule_single_event(time(), 'MY_ACTION');
}
add_action('save_post', 'MY_CRON');
function MY_FUNCTION(){
// YOUR CODE HERE
}
add_action('MY_ACTION', 'MY_FUNCTION');
It will avoid running complex functions on hooks that you want to be snappy. It could be 'save_post', a call via AJAX or like in my case a new order in Woocommerce. It's outlined in more detail in these articles:
- Asynchronous functions in Wordpress
- Use WP Cron to Trigger Asynchronous Background Tasks in WordPress on Post Save or Update
I was hoping to get some opinions from other developers about this pattern.
My problem with this approach is that a) if you have low traffic on your site it may never run due to the way how WP Cron works. And b) if it's really complex stuff you are doing that takes, say, 10 seconds to complete, won't that delay the page rendering the next time WP Cron is triggered by a page load? So my admin actions are really snappy and I close the browser but the next user who is visiting the site is getting an additional 10 seconds loading time? So all I'm doing is passing on the waiting time to somebody else? In some cases this could even be myself.
So my conclusion was to disable WP Cron and schedule a call to wp-cron.php?doing_cron via crontab. But won't that block my site while it's running as well?