How to use cron in linux
Access the crontab file
The crontab file contains the list of tasks scheduled for a specific user. To access this file, you can run the following command in the terminal:
crontab -e
This will open the crontab file in the default text editor.
Edit the crontab file
Inside the crontab file, you will find lines in the following format:
* * * * * command_to_execute
Each field separated by spaces corresponds to:
Minute (0-59)
Hour (0-23)
Month Day (1-31)
Month (1-12)
Day of the week (0-7, where both 0 and 7 represent Sunday)
You can customize these fields according to your needs. To schedule a task, add a new line with the desired format and the command you want to execute at the scheduled time.
For example, to run a script called backup.sh every day at 2:30 AM, you can add the following line:
30 2 * * * /path/to/script/backup.sh
It is important to remember that if you do not specify the minute but only the hour, for example
* 5 * * * /path/to/script/backup.sh
You will be scheduling to run at every minute of that scheduled time and this could lead to problems depending on the script.
Saving and exiting the crontab file
After editing the crontab file, save the changes and close the text editor. In most editors, you can do this by pressing Ctrl + X, followed by Y and finally Enter.
Verify scheduled tasks
You can check the scheduled tasks in your crontab by running the following command:
crontab -l
This will display a list of the tasks scheduled for your user.
Delete a scheduled task
If you want to delete a scheduled task, you can open the crontab file with the crontab -e command and delete the line corresponding to the task you want to delete. Save the changes and close the file.
Make sure that the permissions of the file or script you want to run are set correctly. If you want to receive email notifications when a task is completed, you can redirect the standard output to your email address within the command line. For example:
30 2 * * * /path/to/script/backup.sh >/dev/null 2>&1 | mail -s "Task completed" your@email.com
There are many more options and advanced features available that you can explore by consulting the official cron command documentation.
When creating cron scripts, remember that the PATH and other environment variables of the terminal you use and cron are different, that is why it is recommended to use absolute paths for the executables you use in cron.