这几天遇到一个问题,每个用户有一个守护进程,为了这个守护进程同时只运行一个,所以加了一个文件锁,然而机器要是重启的话,这个文件锁是没法删掉的,重启之后就导致守护进程无法启动了。
一直在找一钟机制,能够在crontab脚本运行之前执行,不是类似rc.d,因为这个是针对root账号,要处理到其他账号的文件锁,就需要针对每一个账号的文件锁都删除一遍,今天发现了crontab的特殊标签,reboot,可以在每次重启后执行一次,触发时机是在crontab其他定时任务之前执行,完美契合我的需求。
具体用法是这样的:
@reboot rm -f ~/monitor_running/monitor_daemon.sh.lock
* * * * * /home/bernie/monitor_running/monitor_daemon.sh
*/10 * * * * /home/bernie/monitor_running/bash/get_branches_list.sh
这样就可以保证在daemon进程运行之前,先将文件锁删除,设置好最初状态。
同时,crontab 还有其他的特殊标签,如下
@reboot : Run once after reboot. 重启时执行一次
@yearly : Run once a year, ie. "0 0 1 1 *". 一年执行一次,1月1号0点0分执行
@annually : Run once a year, ie. "0 0 1 1 *". 一年执行一次,1月1号0点0分执行
@monthly : Run once a month, ie. "0 0 1 * *". 一月执行一次,每月1号0点0分执行
@weekly : Run once a week, ie. "0 0 * * 0". 一周执行一次
@daily : Run once a day, ie. "0 0 * * *". 一天执行一次
@hourly : Run once an hour, ie. "0 * * * *". 一小时执行一次