Scheduled tasks in Linux cron
Introduction
wiki
cron is a classic daemon (a computer program in UNIX-like systems),
used to periodically run tasks at a specified time.
Regular actions are described by instructions placed in crontab files and
in special directories.
The name cron is derived from the Greek word χρόνος (chronos) - time
(in English - chronos).
In systemd-based systems cron is effectively replaced by the built-in systemd.timer mechanism.
crontab files created for individual users are located in the directory
/usr/spool/cron/crontabs/
or
/var/spool/cron/tabs/.
Editing them manually is not recommended; the command
crontab -e
.
Files
crontab
, used to manage the whole system, are located in the directory
/etc/cron.d/.
In addition, in the directories
/etc/cron.daily/, /etc/cron.weekly/ and /etc/cron.monthly/
automatically launched programs are placed (daily, weekly or monthly).
Run the script every minute
crontab -e
*/1 * * * * script.sh
Or simply
* * * * * script.sh
By default cron runs scripts from the home directory
Running from other directories
To run a script from another directory - you first need to go into it
* * * * * cd monitoring/new_scripts && $(which bash) script.sh
cron will change into the desired directory and then, seeing &&, will understand that
it needs to do AND run the script.
A logical or can be set with ||
Python script on a schedule
To run a .py script from an arbitrary directory - go to
it and execute $(which python3) file name
For example:
crontab -e
* * * * * cd python_scripts && $(which python3) script.py
Article author: Andrei Olegovich