Cron is a powerful utility for time-based scheduling of jobs in Unix-like operating systems including Linux. It runs as a daemon and can be used to schedule jobs such as commands or shell scripts to perform backups, schedule updates plus many more, that run periodically and automatically in the background at specific times, dates, or intervals.
One limitation of cron is that it assumes a system will run forever; so it is suitable for servers other than desktops machines. Additionally, you can schedule a task on given or later time, using the ‘at’ or ‘batch’ commands: but the task is only run once (it’s not repeated).
In this article, we will explain how to allow a normal system user to run or execute a PHP script via a cron job scheduler in Linux.
You can schedule jobs using crontab (CRON TABle) program. Each user can have their own crontab file which is made up of six fields for defining a job:
- Minute – accepts values between 0-59.
- Hour – accepts values between 0-23.
- Day of Month – stores values between 1-31.
- Month of the year – stores values between 1-12 or Jan-Dec, you can use first three letters of each month’s name i.e Jan or Jun.
- Day of week – holds values between 0-6 or Sun-Sat, Here also you can use first three letters of each day’s name i.e Sun or Wed.
- Command – command to be executed.
To create or edit entries in your own crontab file, type:
$ crontab -e
And to view all your crontab entries, type this command (which will simply print the crontab file to std output):
$ crontab -l
However, if you are a system administrator and want to execute a PHP script as another user, you need to schedule it in the /etc/crontab file or root user’s crontab file which support an extra filed for specifying the username:
$ sudo vi /etc/crontab
And schedule your PHP script to be executed like this, specify the username after the timing section.
0 0 * * * tecmint /usr/bin/php -f /var/www/test_site/cronjobs/backup.php
The above entry executes the script /var/www/test_site/cronjobs/backup.php everyday at midnight as user tecmint.
If you want to execute above script automatically every ten minutes, then add the following entry to crontab file.
*/10 * * * * tecmint /usr/bin/php -f /var/www/test_site/cronjobs/backup.php
In the above example, the
*/10 * * * * represents when the job should happen. The first figure shows minutes – in this scenario, on every
"ten" minute. The other figures show, respectively, hour, day, month and day of the week.
You may also like to read these following related articles.
- Using Shell Scripting to Automate Linux System Maintenance Tasks
- 12 Useful PHP Commandline Usage Every Linux User Must Know
- How to Run PHP Codes in Linux Terminal
- 30 Useful Linux Commands for System Administrators
That’s all! We hope you find this article useful. If you have any questions or extra ideas to share concerning this topic, use the comment form below.