How to Cron Job in CentOS 7/8
A cron job is scheduled operation which can execute a script or an API at any defined interval.
To create a cron job in a CentOS Server you’ll need to edit a file called CronTab.
CronTab is a configuration file that contained commands that are read by Cronie, a command scheduler that is supposedly already installed in your CentOS server.
To edit the crontab file,
EDITOR=nano crontab -e
To creadte a scheduled task in Cron,
* * * * ping http://www.example.com
The first 5 fields of a crontab command define
- minute (0-59)
- hour (0-23)
- day of the month (1-31)
- month (1-12)
- day of the week (0-6)
An asterisk, * in a time runs the command at every valid value.
After first five field that define the schedule, next field is a shell command that is supposed to be executed.
Example,
To ping a web address at every minute,
* * * * ping http://www.example.com
To run a php script at every 2 minutes
*/2 * * * * php /var/www/html/myscript.php
To hit an GET REST API every week
0 0 * * 0 curl https://example.com/api/some_api
You can test out the required fields values for creating a schedule on crontab.guru
Some of the examples for creating a schedule
* * * * *
– Runs the command every minute.12 * * * *
– Runs the command 12 minutes after every hour.0,15,30,45 * * * *
– Runs the command every 15 minutes.*/15 * * * *
– Runs the command every 15 minutes.0 4 * * *
– Runs the command every day at 4:00 AM.0 4 * * 2-4
– Runs the command every Tuesday, Wednesday, and Thursday at 4:00 AM.20,40 */8 * 7-12 *
– Runs the command on the 20th and 40th minute of every 8th hour every day of the last 6 months of the year.