6

I cannot get a Wordpress cron to trigger. I am trying to run this code to see if I can get an email sent to me hourly.

It's taken directly from the Wordpress examples here: http://codex.wordpress.org/Function_Reference/wp_schedule_event. Except I removed underscores (see caveat in documentation).

The code is running in my theme functions.php file. The cron seems to be registered but the prefixdothishourly function does not get fired (as far as I can tell.)

add_action( 'wp', 'prefixsetupschedule' );

/**
 * On an early action hook, check if the hook is scheduled - if not, schedule it.
 */
function prefixsetupschedule() {
    if ( ! wp_next_scheduled( 'prefixhourlyevent' ) ) {
        wp_schedule_event(time(), 'hourly', 'prefixhourlyevent');
    }
}

add_action( 'prefixhourlyevent', 'prefixdothishourly' );

/**
 * On the scheduled action hook, run a function.
 */
 function prefixdothishourly() {
     return wp_mail("[email protected]", "Notification TEST", "TEST", null);
 }

2 Answers 2

7

Turns out I had to set the ALTERNATE_WP_CRON flag in wp-config.php to make this work:

define('ALTERNATE_WP_CRON', true);
1

The ALTERNATE_WP_CRON basically does a transparent redirect on a user visiting your site and could result in a doing_wp_cron query parameter added to the URL.

If for any reason your WordPress cron jobs are failing due to too much load or due to too little traffic on the website, it may be a good option to switch to a server side/external cron job to fire the WordPress cron for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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