常用命令:

# 列出某个用户cron服务的详细内容
crontab -l
# 删除没个用户的cron服务
crontab -r
# 编辑某个用户的cron服务
crontab -e
# 重启服务
sudo /etc/init.d/cron restart
# 暂停服务
sudo /etc/init.d/cron stop
# 开启服务
sudo /etc/init.d/cron start

编辑一项任务:

ubuntu 定时任务 Crontab_python


例如:

每分钟执行一次

* * * * * python hello.py

每小时的第12分钟执行一次

12 * * * * python hello.py

每小时的第12分钟和第30分钟执行一次

12,30 * * * * python hello.py

每天的5点12分钟执行一次

12 5 * * * python hello.py

每月的1号的5点12分钟执行一次

12 5 1 * * python hello.py

每年的6月1号的5点12分钟执行一次

12 5 1 6 * python hello.py

每周1的5点12分钟执行一次(周日是0)

12 5 * * 1 python hello.py

每3个小时的第12分钟执行一次

12 */3 * * * python hello.py

每小时的0-5分钟, 每分钟执行一次

0-5 * * * * python hello.py

简单的测试:

在用户目录下面生成log.txt文件, 并每分钟写入一次时间。
​​​* * * * * date >> ~/log.txt​

使用过程的一些坑

例如命令: ​​* * * * * cd /home/hjl/test/ && python test.py​

test项目的环境是anaconda3, 也已经添加好了环境变量, 默认执行的anaconda3的python。
我发现, 直接在终端输入: ​​​cd /home/hjl/test/ && python test.py​​​ 可以完美运行, 但是上面的定时任务并没有执行。后来打印错误发现, test.py文件里面的opencv没有导入成功, 查找原因发现, crontab运行时, 所使用的python环境并不是anaconda里面的python环境, 而是系统自带的python3.5。
于是, 在crontab里面强制说明python解释器, 解决了问题。
​​​cd /home/hjl/test/ && /home/hjl/anaconda3/bin/python test.py​