Shell脚本实现每个工作日定时执行指定程序

我们可能会遇到这样的情景:必须在每个工作日定时执行Linux服务器上的某个程序。那么有没有办法实现这一功能呢?答案是肯定的。我们可以运用Shell脚本简单实现这一功能。     

原理很简单,Shell脚本内部每隔1秒查询一次当前时间、日期以及星期数,当检测到当前星期数week非0或6(0代表星期天,6代表星期六)且时间curTime大于指定时间startTime时,执行指定的程序program。为了保证每天仅执行一次指定程序program,还引用了变量isFirstTime做标记。具体代码如下:

 1 #!/bin/sh
 2 
 3 #Section configuration(配置部分)
 4 #Task Time ,example:203000(Time 20:30:00);190000(Time 19:00:00);
 5 startTime=113200
 6 #the programs you want to execute(要执行的程序)
 7 program=ps
 8 
 9 #Section promgram (程序执行部分)
10 perDate=$(date "+%Y%m%d")
11 isNewDay=1
12 isFirstTime=1
13 
14 echo 'Task schedule Time: ('$startTime') program: ('$program') Waiting...'
15 
16 while true ; do
17     curTime=$(date "+%H%M%S")
18     curDate=$(date "+%Y%m%d")
19 
20     #Check week day(周末不执行)
21     week=`date +%w`
22     if [ $week -eq 6 ] || [ $week -eq 0 ];then
23         isNewDay=0
24         sleep 1
25         continue
26 
27     else
28         #check and run script(工作日执行)
29         if [ "$isNewDay" -eq "1" ];then
30             if [ "$curTime" -gt "$startTime" ];then
31                 if [ "$isFirstTime" -eq "0" ];then
32                     echo 'The program ('$program') Running...'
33                     $program
34                     echo 'The program ('$program') Stopped...'
35                 fi
36                 isNewDay=0
37             else
38                 if [ "$isFirstTime" -eq "1" ];then
39                     echo 'New Day: ('$curDate') Task schedule Time: ('$startTime') Waiting...'
40                     isFirstTime=0
41                 fi
42 
43             fi
44         else
45             #new day start(开始新的一天)
46             if [ "$curDate" -gt "$perDate" ];then
47                 echo 'New Day: ('$curDate') Task schedule Time: ('$startTime') Waiting...'
48                 isNewDay=1
49                 perDate=$curDate
50             fi
51         fi
52         sleep 1
53     fi
54 done

 

 

该Shell脚本的功能为每个工作日的11点32分执行一次ps命令,执行的效果如下图所示。

 

Shell脚本实现每个工作日定时执行指定程序

当然该脚本只是为了演示这一定时原理,实际应用中可以指定其他的程序或者脚本,并利用nohup命令让其后台运行。

原文地址:http://ju.outofmemory.cn/entry/2058

转载于:https://www.cnblogs.com/shujuxiong/p/9023254.html