Cron is a utility for scheduling tasks in the Linux operating system. It allows you to run scripts or commands automatically at certain times, intervals or events.
To use Cron, you need to create a crontab
file that contains a list of tasks and time intervals when they should be executed. Each task in crontab is a string that consists of five fields separated by spaces:
* * * * * command_to_execute
- - - - -
| | | | |
| | | | +----- day of the week (0 - 6) (Sunday = 0 or 7)
| | | +------- month (1 - 12)
| | +--------- day of the month (1 - 31)
| +----------- hour (0 - 23)
+------------- minutes (0 - 59)
The *
stands for any value, for example, if the minutes field contains an *
, the task will run every minute. If you want to set a specific value for a field, for example, every day at 3 am, you should write 0 3 * * * * *
.
To create or modify a crontab file, use the crontab -e command. Each user can have their own crontab file, as well as the system file /etc/crontab
, which contains tasks that run as the root user.
There is a cronjob
command that allows you to run tasks inside Docker containers. It works similarly to crontab
, but tasks can be run inside the container instead of the host system.
To start using Cron in Linux, follow these steps:
1. Open a terminal and type the command crontab -e
. This will open the crontab file for the current user.
2. Add a task to the crontab file according to the field format described above. For example, if you want to run the every_hour.sh
script every hour, add the line 0 * * * * * * /path/to/every_hour.sh
.
3. Save your changes and close the file.
4. Verify that the task has been added to crontab by using the crontab -l
command. It will display a list of all tasks added to crontab
.
5. Verify that the task is running as scheduled using the tail -f /var/log/syslog
command. You will see the output related to the task execution.
6. If you want to remove a task from crontab
, use the crontab -r
command.
There are some important points to keep in mind:
crontab
. But if you want to execute a script, make sure it has execute permissions(chmod +x /path/to/script.sh
).sudo crontab -e
command to open the crontab
file for the root user.Note that the time specified in crontab
will match the time on the server running Cron. If you are using a remote server, make sure that the time on the server is configured correctly.