Setting up PHP Cron Jobs

At Gift List Central, we’ve been setting up a few cron jobs – which are basically scheduled jobs that run at intervals you specify. So, for example, we have a job which runs daily to deactivate gift lists which have passed their due date.

Because we have cPanel, we are able to set up cron jobs from the web interface. This is useful, because PHP doesn’t provide you with any kind of cron natively. You can get scripts which simulate cron (pseudo-cron), but the downside to this is that if someone doesn’t visit your site, the cron job doesn’t get run. It also adds overhead into your script, as the crontab has to be checked every page load.

So, Unix cron is a good choice. The problem I had was – what command to run? There are various options: you can load up PHP natively (i.e. run the php interpreter from the command line and call your script directly). However, as we’re using CodeIgniter that’s not really an option – CodeIgniter expects to be called from the web. I had our code to be run regularly mapped to a controller, so /cron/deactivate_expired would execute the correct code and output a report – so really we needed to go in via the web.

No problem, wget to the rescue! wget is a small command line tool which will download files from remote servers for you, given a URL.

This is the actual command line we ended up using:

wget -q -O deactivate_expired.log

Let me just explain that. wget is the name of the executable. -q turns on ‘quiet mode’ – this basically means wget doesn’t produce any output. If you don’t use this option, you will be emailed each time the cron job runs – probably not what you want! -O deactivate_expired.log writes out the output of our controller function to a log file. So, if our controller outputs “Job starting at … Job finished at…”, that will be written to the file.

Lastly, the URL is the address of the controller function we want to call which actually executes our code.

So there you have it – hopefully this will help someone else getting PHP cron to work!


Leave a Reply

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

Related posts

Like this? Subscribe to my Substack.