How to use the cron command in Linux to schedule tasks?
To use the cron command for scheduling tasks, follow the following steps:
- Open the terminal and log in as the root user.
- Use the command crontab -e to edit the cron task list.
- In the cron job table, each line represents a scheduled task. Each line contains the time when the task will be executed and the command to be executed. For example, the following syntax represents running a command at midnight every day:
- Every day at midnight, run the command.
- The code “0 0 * * *” stands for midnight every day, and “command” is the command to be executed.
- Special characters can be used to represent the execution time of the task.
- “*” represents any time.
- “/n” represents executing once every n units of time, for example “/5” means executing once every 5 minutes.
- “n” represents a specific unit of time, for example, “3” represents the third unit of time.
- Time units can be in minutes (0-59), hours (0-23), dates (1-31), months (1-12), or weekdays (0-7, where 0 and 7 both represent Sunday).
- After finishing editing the cron task table, save and exit the editor.
- You can use the command crontab -l to view the current cron task table.
Important points to note:
- Each command in the cron tab requires its own line when editing.
- To remove all tasks from the crontab, you can use the crontab -r command.
- The format of a cron job table may vary depending on the operating system. In some Linux distributions, system-level cron jobs can be edited in the /etc/crontab file.