Chinaunix首页 | 论坛 | 博客
  • 博客访问: 368849
  • 博文数量: 61
  • 博客积分: 2451
  • 博客等级: 上尉
  • 技术积分: 650
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-06 21:24
文章分类

全部博文(61)

文章存档

2012年(1)

2011年(44)

2010年(16)

分类:

2011-05-02 23:19:22

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