CentOS 7 regularly executes Python scripts
In CentOS, crontab can be used to process scheduled tasks.
1、 Installation of crontab
By default, crontab is already installed in CentOS 7. If it is not installed, you can install it through Yum or up2date.
yum install crontabs
2、 Timing syntax description of crontab
In corntab, a line of code is a timed task, and its syntax structure can be understood through this diagram.
|*||Represents all within the value range|
|/||Stands for “every”|
|–||Represents from a number to a number|
|,||Represents discrete values (list of values)|
Some common ways of writing time
|* * * * *||Execute every minute|
|* */4 * * *||Every 4 hours|
|0 4 * * *||Every day at 4:00|
|0 12 */2 * *||It is executed every 2 days and starts running at 12:00|
|* * * * 0||Every Sunday|
|* * * * 6,0||Every Saturday and Sunday|
|5 * * * *||Executed in the 5th minute of every hour|
3、 Set scheduled tasks
Writing Python scripts
# test.py print("hello world!")
Upload to the specified directory through finalshell
[[email protected]_0_8_centos script_py]# whereis crontab crontab: /usr/bin/crontab /etc/crontab [[email protected]_0_8_centos script_py]# vim /etc/crontab #Add at the end of file * * * * * root /usr/bin/python3 /data/script_py/test.py > test.log #Execute as root every minute. Run test.py with python3 and output to test.log
systemctl restart crond
[[email protected]_0_8_centos script_py]# cat /root/test.log hello world!
It is very important to write the command with an absolute path, otherwise the scheduled run fails. Therefore, we need to find out the specific path of Python first.
#View the path of python2 installed by default [[email protected]_0_8_centos ~]# which python /usr/bin/python #View the path to the self installed Python 3 [[email protected]_0_8_centos ~]# which python3 /usr/bin/python3