1

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:

  1. Asynchronous functions in Wordpress
  2. 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?

1

...if you have low traffic on your site it may never run due to the way how WP Cron works

In your particular example it should always fire. Since save_post runs just before a browser redirect, the subsequent request back to the edit screen will fire the cron schedule.

...won't that delay the page rendering the next time WP Cron is triggered by a page load?

No. If you check out spawn_cron(), you'll see it fires a parallel request to process the schedule.

From the codex:

Send request to run cron through HTTP request that doesn't halt page loading. Will not run more than once every 60 seconds.

  • I looked ad spawn_cron() before but overlooked that it calls wp_remote_post with the blocking parameter set to false. What you say makes sense. Thank you. – Jan Beck Apr 16 '14 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.