ubuntu定时执行python脚本实例代码
原文链接:https://vien.tech/article/157
前言
本文将介绍ubuntu系统下如何定时执行shell脚本、python脚本,ubuntu系统有一个定时任务的管理器crontab,我们只需要编辑定时任务,然后重启定时任务服务就好了。
crontab
编辑定时任务
crontab-e
参数定义:
- -u指定用户,--l列出用户任务计划,
- -r删除用户任务,
- -e编辑用户任务
英文介绍:
#Editthisfiletointroducetaskstoberunbycron.
#
#Eachtasktorunhastobedefinedthroughasingleline
#indicatingwithdifferentfieldswhenthetaskwillberun
#andwhatcommandtorunforthetask
#
#Todefinethetimeyoucanprovideconcretevaluesfor
#minute(m),hour(h),dayofmonth(dom),month(mon),
#anddayofweek(dow)oruse'*'inthesefields(for'any').#
#Noticethattaskswillbestartedbasedonthecron'ssystem
#daemon'snotionoftimeandtimezones.
#
#Outputofthecrontabjobs(includingerrors)issentthrough
#emailtotheuserthecrontabfilebelongsto(unlessredirected).
#
#Forexample,youcanrunabackupofallyouruseraccounts
#at5a.meveryweekwith:
#05**1tar-zcf/var/backups/home.tgz/home/
中文解释:
格式
mhdommondowcommand
以上为缩写,这里提供全拼对照:
minute(m), hour(h),dayofmonth(dom),month(mon),dayofweek(dow)
含义如下:
- m每个小时的第几分钟执行该任务
- h每天的第几个小时执行该任务
- dom每月的第几天执行该任务
- mon每年的第几个月执行该任务
- dow每周的第几天执行该任务-command指定要执行的程序
分 小时 日 月 星期 命令
0-59 0-23 1-31 1-12 0-6 command
其他:
- 其中星期中0表示周日。
- *代表任何时间,比如第一个分钟,用*就代表每一小时的每一分钟都执行
- -表示区间,比如1-3
- ,如果区间不连续,可以用,例如1,3,6编辑完成后wq保存退出
重启服务
servicecronrestart
注意事项
注意,一定要用绝对路径。否则可能会执行失败。
比如,我们要执行
pythonbwh.py
那么你需要干的第一件事是
whichpython
以此来查看python命令的真正路径
root@ubuntu:~#whichpython /root/.pyenv/shims/python
然后,查看bwh.py的全路径,在bwh.py所在文件夹下
pwd /app/python/blog
然后路径便为
/app/python/blog/bwh.py
所以整条记录应该这样编辑
09***/root/.pyenv/shims/python/app/python/blog/bwh.py>/tmp/new_blog_bwh.log
上面的记录是指每天9点整执行/root/.pyenv/shims/python/app/python/blog/bwh.py并将打印日志输出到/tmp/new_blog_bwh.log
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。