crontab定时执行python

crontab

编辑定时任务

crontab -e
# -u 指定用户, - -l 列出用户任务计划,
# -r 删除用户任务,
# -e 编辑用户任务

英文介绍:

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/

中文解释:

m h dom mon dow command   #格式
minute (m),  hour (h), day of month (dom), month (mon), day of week (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 保存退出

重启服务

service cron restart

注意事项
注意,一定要用绝对路径。否则可能会执行失败,比如,我们要执行

python3 run	.py

那么你需要干的第一件事是

which python3

以此来查看python命令的真正路径

/usr/bin/python3

然后,查看run.py的全路径,在run.py所在文件夹下执行pwd

pwd  #查看绝对路径
/root/run.py

所以整条记录应该这样编辑

0 23 * * * /usr/bin/python3 /root/run.py > /root/run.log 2>&1

上面的记录是指每天23点整执行并将打印日志输出到/root/run.log

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值