Running wordpress cron jobs on a linux server

I was having an issue with a site that required a database intensive update 4 times a day, we are talking 1000s of  mysql rows updated/deleted/inserted each time. It seemed to be getting by nicely on a test server using wordpress simple cron scheduler. Going live however was a different story, epic failures and error 500s on the clients live website.

Instead of running the script as a hook/function on wordpress I ran it instead using the servers direct crontab, problem solved.The simplest way to get your wordpress functions into an external PHP script is by calling the wp-blog-header.php script as follows

require_once('path-to-directory/wp-blog-header.php');

Remember on your linux server use type -a php to find your php interpreter location

type -a php

You should get something along the lines of

php is /usr/bin/php

Then at the top of your actual PHP script you’re going to run make sure you add the following line

#!/usr/bin/php
<?php
require_once('/path-to-website-directory/wp-blog-header.php');

/* The rest of your code goes below */

?>

 

You may encounter an issue with running your script on the server if your file is not formated correctly and the server complains about not being able to find your PHP interpreter

/usr/bin/php^M: bad interpreter: No such file or directory

Simply open your script using VIM and do the following

:set fileformat=unix
:wq

Your file should now run as any normal PHP file would on a wordpress setup

Leave a Reply

Your email address will not be published. Required fields are marked *