> shell编程 >

shell实现秒级crontab计划任务

crontab是linux自带的计划任务程序,可以实现分,时,日,周,月。

但是crontab有两个缺陷:
1.最小粒度为分,对于秒不支持
2.若是上一个任务的执行时间超过下一个任务的开始时间的话,就会出现两个任务并行的现象,这样任务会越积越多,最后系统挂了。
这周在项目里需要实现每隔10秒去执行任务的功能,因此写了个shell程序:
1.可以自定义程序执行时间间隔,
2.使用的是deamon方式,产生两个进程,父进程监控子进程,若是子进程挂了,父进程重新启动子进程,子进程负责每隔10秒钟执行任务;
3.而且当任务执行时间超长时,不会出现两个任务同时执行的现象,下一个任务只会延后。也可以用后台运行方式运行任务,这样和crontab的效果一样
4.若是时间间隔为10秒,而任务只执行了1秒,则sleep 9秒后,执行下一次任务
5.若是把sleep改为usleep的话可以精确到微秒

 


  1. #运行执行 sh /Application/sdns/trigger/task_crontab.sh >> /Application/sdns/log/crontab.log 2>&1  
  2.  
  3. #要定时执行的脚本,注意:不使用后台运行,则若是超过10秒的话,下一次会延迟,若是使用后台执行的话,有可能出现两个任务并行的问题  
  4. dlc_cmdline="sh /Application/sdns/trigger/dotask.sh >> /Application/sdns/log/dotask.log";  
  5. #本shell脚本的执行路径  
  6. dlc_thiscmd="sh /Application/sdns/trigger/task_crontab.sh >> /Application/sdns/log/crontab.log 2>&1" 
  7. #任务执行时间间隔  
  8. dlc_task_timeout=10;  
  9. #是否后台执行deamon  
  10. is_deamon=$1;  
  11. #deamon,父进程  
  12. if [ "$is_deamon" == "--deamon" ]  
  13. then 
  14. echo "deamon start" 
  15. while [ 1 ]  
  16. do  
  17. date +"%F %T $dlc_thiscmd is started";  
  18. #调用子进程  
  19. $dlc_thiscmd  
  20. date +"%F %T $dlc_thiscmd is ended";  
  21. done  
  22. fi  
  23.  
  24. #子进程的代码  
  25. while [ 1 ]  
  26. do  
  27. date +"%F %T $dlc_cmdline is started" ;  
  28. #记录本次程序开始时间  
  29. dlc_start_time=`date +%s`  
  30. #执行任务  
  31. $dlc_cmdline  
  32. #计算和时间间隔的差距  
  33. dlc_sleep_time=$(($dlc_task_timeout+$dlc_start_time-`date +%s`));  
  34. echo "sleep_time=[$dlc_sleep_time]";  
  35. #不够10秒,则sleep到10秒  
  36. if [ "$dlc_sleep_time" -gt 0 ]  
  37. then 
  38. sleep $dlc_sleep_time;  
  39. fi  
  40. date +"%F %T $dlc_cmdline is ended";  
  41. done  


(责任编辑:IT)