To schedule a task in Linux using cronjobs, you’ll edit the crontab file using the crontab -e
command, add a new entry specifying the execution time and the command to run, then save and close the file.
Here’s a more detailed breakdown:
1. Open the crontab file:
- Use the command
crontab -e
in the terminal. This will open the crontab file for the current user in your default text editor. - If you’re using
crontab -e
for the first time, you may be prompted to choose an editor. Nano is a user-friendly option.
2. Add a cron job entry:
- Each cron job entry follows a specific format:
- Minutes: 0-59 (e.g.,
0
for the start of the hour). - Hours: 0-23 (e.g.,
10
for 10 AM). - Days of the month: 1-31 (e.g.,
1
for the first day of the month). - Months: 1-12 (e.g.,
1
for January). - Days of the week: 0-7 (0 and 7 represent Sunday).
- Command: The command or script you want to execute.
- Minutes: 0-59 (e.g.,
- Example: To run a script
/path/to/my_script.sh
every Sunday at 3 AM, you would add the following line:
0 3 * * 0 /path/to/my_script.sh
``` [9]
- You can use special characters like
*
(any value),-
(range),,
(multiple values), and*/
(increment) to specify the execution time [6, 8, 15].
3. Save and close the crontab file:
- Save the changes to the crontab file (e.g., press Ctrl+X, then Y, then Enter in Nano) [13].
- The changes will be automatically applied [13].
Example Scenario:
Let’s say you want to run a backup script /home/user/backup.sh
every Monday at 2:15 AM. The cron job entry would be: