linux下循环执行某个任务的命令是crontab 其背后是crond服务做支持
如果想要定时执行一个任务,可以使用crontab命令
crontab -e 直接编辑
0 0 * * * /root/soft/one.sh
上面的意思是每天凌晨执行 /root/soft/one.sh这个脚本
# 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
# | | | | |
# * * * * * command to be executed
*代表任何时刻都能接受,就像上面的那样,任何天,任何个月,任何周都能执行one.sh这个脚本
其中最后一个0-7有8个取值,0和7都代表周日
,代表时间间隔的意思
eg: 0 3,5,7 * * * /root/soft/one.sh 表示每天的3、5、7点的第一分钟起执行one.sh
- 代表时间段
eg:0 3-8 * * * * /root/soft/one.sh 表示每天的3、4、5、6、7、8点的第一分钟执行one.sh脚本
/ 表示每个N个时间单位执行一次
eg: */5 * * * * /root/soft/one.sh 表示每隔5分钟执行一次/root/soft/one.sh
crontab -l 可以直接查看当前用户的定时任务
如果想要取消就直接crontab -e删除自己的定时任务即可
设置允许的使用者即哪些用户可以使用,哪些用户不能使用
白名单:/etc/cron.allow 若不在这个档案中就不能使用crontab
黑名单:/etc/crond.deny 若在这个档案中就不能使用crontab
一般情况下在/etc/目录下只留一个文件
建立crontab 任务后,这些任务会被记录到/etc/spool/cron/username文件中 其中username是当前用户的用户名
此外。crontab的任务的日志会被记录到/var/log/cron这个文件中
以上说的都是基于个人用户的定时任务,如果说有一个系统级别的定时任务,那么应该怎么办呢?
系统级别的定时任务在 /etc/crontab中编辑 不过语法略有不同,需要制定用户名,表示是哪个用户的系统级别的定时任务
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# 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
*/1 * * * * root /root/soft/one.sh
其中:
shell 表示用的是哪种shell
PATH:指shell的搜寻路径,说白了就是环境变量
MAILTO:表示如果如果定时任务发生异常,发送邮件给谁
还有一种系统级别的定时任务就是编辑一个新文件放到 /etc/cron.d/目录下
新文件格式如下
*/10 * * * * user-name /root/soft/one.sh
和上面的格式一样
这就是Linux的crontab定时任务