CRON tasks or CRON jobs are automated web server processes. The word CRON is derived from the name of the Greek God of time Chronos. CRON jobs themselves are set to run at certain points in time, hence the name. They can run once or periodically. Most dedicated hosting control panels have a section you can use to setup these CRON Jobs. A Common example of a CRON jobs is a data import system from a social media network such as Twitter.
Creating a CRON job
When creating a CRON job you need to define the path to the php executable, the path to the file to be processed and the time or frequency of the scheduled task. The most frequently you can set a task to run is every minute. This you would define by using wild cards for each of the time settings i.e. * for minutes, * for hours, * for day month and so on. A problem that arose for me was that I required a CRON task that had to run at intervals lower than one minute. There was for this a simple solution, but it was one of those that I could not see for looking!
The Sleep Function: PHP
PHP has a function called sleep, all it does is allow a process to pause for a set number of seconds. So to pause a PHP script for fifteen seconds you would include ‘sleep(15);' in your PHP file. This simple function can be applied to a script that runs every minute to allow it to execute a function every fifteen seconds. Below is an example of a simple script I have created. It allows you to verify that your server is capable of executing a background task every 15 seconds.
Simply copy the code above and insert into a php file, called for example, test-file.php. Upload this to your server. Configure your CRON job to execute this file every minute, follow this link if you need to read about configuring CRON jobs. After a few minutes download the file timelog.txt. If your CRON job has been correctly configured this file will be found in the same directory as the test file you have just uploaded. The content of this file should be similar to the image below. The timestamps indicate that the task is running every fifteen seconds.