Linux–CentOS定时运行Python脚本

执行所需

  • Linux下安装crontab
  • 符合自己需求的python脚本
    由于自己和公司所使用的是云服务器,均已安装crontab,所以这里略过,有需要的小伙伴可以看看此篇文章

操作步骤

这里有两种方法进行定时任务添加,分别是crontab -e和编辑/etc/crontab。两种方法的语法也略有不同,/etc/crontab的语法比crontab -e多了一个用户字段。

  • crontab -e 用户级,不能设置用户字段
  • /etc/crontab 系统级,只能root用户权限使用,需要设置用户字段

crontab -e

这种方式是用户级的,所有用户的可以使用,实际保存在/var/spool/cron/username中。但有的linux系统加在crontab -e会无效,这种方法不会对语法进行校验。具体操作步骤为:

crontab -e

添加定时任务,如每周一3点执行python脚本

0 3 * * 1 python /data/www/test.py

wq保存退出,完毕

语法为:

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * command to be executed

/etc/crontab

直接编辑/etc/crontab

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

直接编辑/etc/crontab 比 crontab -e 多了一个用户名字段,该方法是系统级的,必须root权限使用

步骤:

vi  /etc/crontab

在后面添加定时任务,如每周一3点执行python脚本

0 3 * * 1 root python /data/www/test.py

wq保存退出,完毕

具体语法请看此篇文章

抄袭此篇博客

你可能感兴趣的:(Linux–CentOS定时运行Python脚本)