Methods of payment Abuse

Cron in Linux: what is it?

26.02.2023, 13:13
Cron is a utility for scheduling tasks in the Linux operating system. It allows you to run scripts or commands automatically at a certain time, with a certain frequency or at certain events.

How to use it?

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 * sign means any value, for example, if the minutes field contains *, then the task will be executed every minute. If you want to set a specific value for a field, for example, every day at 3 a.m., then you need to 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 /etc/crontab system file, which contains tasks run as root.
 
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.

Using Cron: a step-by-step algorithm

To start using Cron on Linux, follow these steps:
 
1. Open the terminal and enter the crontab -e command. This will open the crontab file for the current user.
 
2. Add the task to the crontab file according to the field format described above. For example, if you want to run the every_hour script.sh every hour, add the line 0 * * * * /path/to/every_hour.sh .
 
3. Save the changes and close the file.
 
4. Check that the task has been added to crontab using the crontab -l command. It will list all the tasks added to the crontab.
 
5. Make sure that the task is running according to the schedule using the tail -f /var/log/syslog command. You will see the output associated with the task execution.
 
6. If you want to delete a task from crontab, use the crontab -r command.
 
Some important points should be taken into account:
you can add both scripts and commands to crontab. But if you want to execute the script, make sure it has execution rights (chmod+x/path/to/script.sh ).
 
if you want the task to be executed with root user rights, use the sudo crontab -e command to open the crontab file for the root user.
 
make sure that the commands and scripts you are running are in the right place and have the correct read and execute permissions.
Note that the time specified in crontab will correspond to 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.