用crontab运行定时任务

以一个Python项目的定时任务为例:

先写好一个run.sh脚本:

#!/bin/bash
/bin/echo "the script start `date`" >> /home/shikanon/log/log.txt
source venv/bin/activate
python getMinuteData.py

然后编写crontab文件,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

创建crontab文件:

> vim getData.cron
> 0 16 * * * /home/shikanon/download/getData/run.sh

表示每天16点运行一次/home/shikanon/download/getData/run.sh命令

创建任务crontab getData.cron
查看用户所有任务crontab -l
删除当前用户所有任务crontab -r
编辑当前用户下的任务crontab -e,当结束编辑离开时,编辑后的文件将自动安装。

更多例子:

(注意单纯echo,从屏幕上看不到任何输出,因为cron把任何输出都email到root的信箱了。)

每天早上6点执行一次

> 0 6 * * * echo "hello world" >> /tmp/test.txt

每两个小时执行一次

> 0 */2 * * * echo "hello world" >> /tmp/test.txt

23点到8点之间每两个小时执行一次

> 0 23-7/2 * * * echo "hello world" >> /tmp/test.txt

23点到8点之间每两个小时执行一次,同时8点执行一次

> 0 23-7/28 * * * echo "hello world" >> /tmp/test.txt

每个月的4号11点执行一次,同时每个周的周一到三11点执行一次

> 0 11 4 * 1-3 echo "hello world" >> /tmp/test.txt

每天的下午4点、5点、6点的5 min、15 min、25 min、35 min、45 min、55 min时执行一次

> 51525354555 161718 * * * echo "hello world" >> /tmp/test.txt

shikanon wechat
欢迎您扫一扫,订阅我滴↑↑↑的微信公众号!