3

Today I've tried to write a Wordpress Cronjob. For testing purposes I wrote a function that sends me an email every hour, but it's not working. I've got a plugin called 'Core Control' which shows me all existing Cronjobs - mine is also listed there. There is also a button "Run now". If I press it, I get the test-mail, so the function itself is correct.

Here is the code for the Cronjob, it is placed inside the functions.php of my theme.

if( !wp_next_scheduled( 'check_cron' ) ) {  
   wp_schedule_event( time(), 'hourly', 'check_cron' );  
}   

add_action( 'check_cron', 'sendit' );

function sendit() {  
    $address = "[email protected]";
    $sender = "Cron_Test";
    $sendermail = "[email protected]";
    $subject = "It works!";
    $text = "Yay, it is working!";

    mail($address, $subject, $text, "From: $sender <$sendermail>");    
}  

There has to be something wrong with the action hook, but I have no idea what's wrong. Or do I need to place the code in some different file?

Some more Info: I now that mail(); does not work on localhost, that's why I created a test blog online. The folder is protected via .htaccess with a password, could that be an issue?

I also checked that my wp-config.php allows Cronjobs.

I also now that the site needs to be visited for the Cronjob to run.

2
  • Are you on WP 3.3? I have been having troube with wp-cron since the upgrade (posts with missed schedule), so maybe it is a general issue.
    – Raphael
    Commented Feb 11, 2012 at 19:34
  • Yes I am also on 3.3.!
    – Sven
    Commented Feb 11, 2012 at 19:57

1 Answer 1

2

Unfortunately the WordPress cron jobs are only triggered when your site is visited (see Codex):

The action will trigger when someone visits your WordPress site, if the scheduled time has passed.

I believe this to get around the fact that many on shared hosting aren't normally allowed to set up cron jobs (at least, not without contacting their host first).

2
  • Do you know if the cron job will run in the same request / process as the site visit which triggers it? i.e. will the site visitor who triggers the cron job experience a delay while the wp cron job runs?
    – codecowboy
    Commented Sep 28, 2013 at 7:15
  • It won't, no. It'll spawn a new one. If that's not allowed, I believe it triggers a http request of the page - that's the 'alternative wp cron', as a bit of hacky workaround for difficult hosts. Commented Sep 28, 2013 at 8:27

Your Answer

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

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