In this post we will see how to schedule task in unix systems with the use of crontab.
Frequently we need to run processes in the background in out web servers like generate thumbnails, execute mantenance MySQl queries, etc. Unix systems have a great tool named cron. This tool allows us to run processes automatically in regular intervals. Also, we can create backups, synchronize files and a much more. To do all these stuff we have crontab.
Crontab
The crontab command is used in Unix systems to schedule other programs to be executed periodicaly. To see what crontabs are currently running in our system, we can run:
1 | user@unix:~$ crontab -l |
To edit the crontabs we can run:
1 | user@unix:~$ crontab -e |
This command will open our editor by default to allow us to edit the crontab. To write our crontabs we can use this format:
1 | user@unix:~$ * * * * * php /var/www/hasheado/script.php |
Explaining the format
As we can see in the above command there are 5 asterisks. The asterisk represent different date and time parts:
- minutes (from 0 to 59)
- hour (from 0 to 23)
- day of month (from 1 to 31)
- month(from 1 to 12)
- day of the week (from 0 to 6) (0 = Sunday)
Executing a command every minute
If we use an asterisk in all parts:
1 | user@unix:~$ * * * * * php /var/www/hasheado/script.php |
This will execute the script /var/www/hasheado/script.php:
- every minute
- every hour
- every day of the month
- every month
- every day of the week
Well that is, I hope it’s helpful, crontab is so powerful.
I will be putting this dazzling insight to good use in no time.