Easy Script to Test your CRON Job

Developers would know this…often times, we setup CRON Jobs to run on specific times to execute a specific file or perform a task but we really don’t know if it’s running as it should.

Now I know many developers choose to have a script that probably logs its execution on a log file somewhere or output it to a TXT file. This is one alternative but I found this little PHP script online on InkPlant. It quite useful because it does the same thing (outputting execution of the main file to a TXT document).

If you are adding a job through crontab, here’s a good way to know if it’s actually running:

1) Create a blank text document named cron_test.txt and upload it into your script’s folder. Change the CHMOD settings or permissions on it to 777 so that its writable by the server.

2) Create a new PHP file called “cron_test.php”. This script will basically execute a task of writing a line of details to cron_test.txt you created in Step 1.

$crontext = "Cron Run at ".date("r")." by ".$_SERVER['USER']."\n" ;
$folder = substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER['SCRIPT_FILENAME'],"/")+1);
$filename = $folder."cron_test.txt" ;
$fp = fopen($filename,"a") or die("Open error!");
fwrite($fp, $crontext) or die("Write error!");
echo "Wrote to ".$filename."\n\n" ;

3) Enter the following line to your Crontab or CPanel if you’re using one.

* * * * * php /yourfolder/cron_test.php

4) You should be able to see all the execution data on “cron_test.txt”.

Hope you found that useful. If you have a neater solution to test CRON jobs, please do share. I would love to know about it.

Leave a Reply

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