CentOS定时运行Python脚本

执行所需

  • Linux下安装crontab
  • 符合自己需求的python脚本

操作步骤

这里有两种方法进行定时任务添加,分别是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保存退出,完毕

crontab语法

学习来源
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容