Crontab——Linux定时执行任务

Crontab >>Linux中定时执行任务的工具

安装: yum -y install 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

操作符:【 * 】 代表所有范围,eg: * * * * *  每分钟执行一次,不管是几点,几小时,几天,几月,星期几。

              【 , 】代表个别的点,eg: 30 9,18 * * * 每天的9:30, 18:30执行一次。

              【 - 】代表自定义的连续区间 eg: 30 9-18 * * *  每天的9点到18点,中间每个小时的第30分钟,就执行。

              【 / 】代表每隔多少时间 eg: 30 */3 * * * 每天从 0点开始,每隔三个小时执行一次

添加定时任务: crontab -e 

然后按 i 进入编辑模式,开始编辑。

注意:最好在文本开头写上 #!/bin/bash 表示可以执行bash脚本,再附上PATH变量,【env】命令可以查询到。

Although cron requires that each entry in a crontab end in a newline character, neither the crontab command nor the cron daemon will detect this error. Instead, the crontab will appear to load normally. However, the command will never run. The best choice is to ensure that your crontab has a blank line at the end. 

                                                                                                                                                                                                                                                                                    - -man 4 crontabs

大意如下:crontab的定时任务之间无符号分割,还是会正常加载,日志也会打印,不报错,但是command不执行。

每条定时命令要空白行隔开,否则可能出现查询日志有执行,但实际命令未执行。

查看定时任务: crontab -l

查看执行日志: cat /var/log/cron 

Centos7 开启cron服务:systemctl start crond;查询cron状态:systemctl status crond

编写.sh文件tips:

:set ff查看编码格式,dos格式可能不会被执行。

:set ff=unix 改变编码格式。

chmod +x filename 赋予.sh文件 执行权限。

执行.py文件tips:

>覆盖输出

>>追加输出

python .py > result.txt 将.py文件的执行结果覆盖输出到result.txt文件中,追加输出 >> 。

猜你喜欢

转载自www.cnblogs.com/hill233/p/12398955.html