+

How to get the most out of wp_cron

November 13, 2012

Cron is an amazing tool, you can have tasks accomplished while you sleep, eat, play videos games, work and anything else. This is awesome if you want to have stuff happen at specific times. WordPress has cron functionality built in, but it is not really cron. It is a pseudo cron, meaning it runs the jobs when the application is running, not when it isn’t, this means that it doesn’t run the tasks unless someone runs the WordPress application by visiting your site, logging into admin, etc.

So it will check every time it loads the site if it needs to run any cron jobs registered in WordPress. If you wanted something to happen exactly at 12:01 am but no one visited your site until 9:00 am the job wouldn’t happen until then, bummer right? Yup, this is a serious drawback to a pseudo cron.

Another pitfall is now that visitor that who visited at 9:00 am has to wait for that job while the site loads, big deal right? Probably not, but if you’re job involves a lot of processing and CPU cycles, it *could* slow down the load time. Perhaps you job is making an API call or something of that nature where it has to talk to another host, then you are waiting on the other server as well. it’s best to just avoid that hassle and let a real cron do the job. Luckily the folks who developed WordPress are super smart and knew that.

Actually this is somewhat of a common feature of php CMS systems, but I have a warm spot in my heart for WordPress. In a couple of quick steps you can have a real cron job running your WordPress registered cron jobs.

  1. First in wp-config.php in your wordpress directory you can disable wp_cron from running in the background:
    
    define('DISABLE_WP_CRON', true);
    
    
  2. Since you have disabled cron jobs in WordPress from running you’ll have to set up a real cron job to execute the cron job in WordPress, if that scares you, you may want to ask for some help, but most hosting providers allow you to set up a cron job relatively easily. A lot of them allow you to even choose the time that it will run from a list of dropdowns so you don’t need to know the correct cron syntax. I won’t get into that in depth, but basically you define ( minute, hour, day, month, and day of the week ); the line below shows a curl execution running the first minute of the hour, every (*) hour, everyday, every month, every day of the week. Curl isn’t the only way to do this, you could use many others, its just my preference.
    
    1 * * * * curl http://yoursite.com/wp-cron.php
    
    

Thats it, then every hour it will run your cron jobs. You can have it run more frequently if you like. For more info checkout this reference or check out this generator and if you need a cron job hosted for you there are services out there such as Cronless

Posted in: General, Tools, Web Development   |   Tags: , ,

Comments are closed.

« Back to Blog