crontab
(1) crontab -e : 修改crontab文件。如果文件不存在会自动创建 (2) crontab -l : 显示crontab文件。 (3) crontab -r : 删除crontab文件。 (4) crontab -ir : 删除crontab文件前提醒用户
{minute} {hour} {day-of-month} {month} {day-of-week} {full-path-to-shell-script} minute: 区间为0-59 hour: 区间为0-23 day-of-month: 区间为0-31 month: 区间为1-12,1是1月,12是12月 day-of-week: 区间为0-7,周日可以是0或7
示例:
(1)在每天00:01运行,即每天凌晨过一分钟。
1 0 * * * /root/bin/hello.sh
(2)每个工作日(Mon - Fri)11:59PM运行
59 23 * * 1,2,3,4,5 /root/bin/hello.sh
(3)下面例子与上面的例子效果一样
59 23 * * 1-5 /root/bin/hello.sh
(4)每5分钟运行一次
*/5 * * * * /root/bin/hello.sh
(5)每个月的第一天1:10pm运行
10 13 1 * * /root/bin/hello.sh
(6)每个工作日11:00pm运行
0 23 * * 1-5 /root/bin/hello.sh
正确写法:
*/60 * * * * /root/bin/hello.sh
以下均为错误写法:
0 * * * * /root/bin/hello.sh # 每小时的0分运行。虽然也是每小时运行一次,但是如果我是在10:20创建crontab,应该在11:20运行,而不是11:00
0 */1 * * * /root/bin/hello.sh # 和上面一样
* */1 * * * /root/bin/hello.sh # 更加错误的写法,分钟要求的是每分钟执行,而小时却要求每小时执行,最终以分钟为准。因此每分钟执行一次。
* * * * * /root/bin/hello.sh * * * * * sleep 30; /root/bin/hello.sh
* * * * * /root/bin/hello.sh * * * * * sleep 10; /root/bin/hello.sh * * * * * sleep 20; /root/bin/hello.sh * * * * * sleep 30; /root/bin/hello.sh * * * * * sleep 40; /root/bin/hello.sh * * * * * sleep 50; /root/bin/hello.sh
flock [-sxon][-w #] file [-c] command -s, --shared: 获得一个共享锁 -x, --exclusive: 获得一个独占锁 -u, --unlock: 移除一个锁,通常是不需要的,脚本执行完会自动丢弃锁 -n, --nonblock: 如果没有立即获得锁,直接失败而不是等待 -w, --timeout: 如果没有立即获得锁,等待指定时间 -o, --close: 在与逆行命令前关闭文件的描述符号,用于如果命令产生子进程时会不受锁的管控 -c, --command 在shell中运行一个单独的命令 -h, --help 显示帮助 -V, --version 显示版本
任务举例:
# hello.lock为是一个锁临时文件 * * * * * flock -xn /root/bin/hello.lock -c '/root/bin/hello.sh' * * * * * sleep 30; flock -xn /root/bin/hello.lock -c '/root/bin/hello.sh'