免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1900 | 回复: 0
打印 上一主题 下一主题

Java实现定时重启windows指定服务 [复制链接]

论坛徽章:
2
丑牛
日期:2014-05-15 09:31:39IT运维版块每日发帖之星
日期:2016-08-19 06:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-05-26 14:32 |只看该作者 |倒序浏览
  1. package com.test.processManagement;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.io.PrintStream;  
  10. import java.text.ParseException;  
  11. import java.text.SimpleDateFormat;  
  12. import java.util.Date;  
  13. import java.util.Timer;  
  14. import java.util.TimerTask;  
  15.   
  16. /**
  17. * <title>ServRebootScheWin</title>
  18. *  
  19. * <project>Exam</project>
  20. *  
  21. * <package>com.test.processManagement</package>
  22. *  
  23. * <file>ServRebootScheWin.java</file>
  24. *  
  25. * <date>2012-7-11</date>
  26. *  
  27. * <brief>本程序用于每天定时重启windows系统上的指定服务,并记录日志</brief>
  28. *  
  29. * @author Wero
  30. *  
  31. */  
  32. public class ServRebootScheWin {  
  33.   
  34.     public static void main(String[] args) {  
  35.         // store the console output  
  36.         final PrintStream console = System.out;  
  37.         if (args.length < 2) {  
  38.             LOG("参数不全,程序将退出...");  
  39.             Runtime.getRuntime().exit(-1);  
  40.         }  
  41.   
  42.         final String timeStr = args[0];// 每天重启时间(HH:mm:ss)  
  43.         final String servName = args[1];// 服务名  
  44.         if (args.length >= 3) {  
  45.             try {  
  46.                 System.setOut(new PrintStream(new FileOutputStream(args[2])));  
  47.             } catch (FileNotFoundException e) {  
  48.                 System.setOut(console);  
  49.                 LOG("日志文件无法建立...");  
  50.             }  
  51.         }  
  52.   
  53.         // convert time string to Date type  
  54.         Date date = null;  
  55.         try {  
  56.             date = new SimpleDateFormat("HH:mm:ss").parse(timeStr);  
  57.         } catch (ParseException e1) {  
  58.             LOG("日期格式(HH:mm:ss)错误,程序将退出...");  
  59.             Runtime.getRuntime().exit(-1);  
  60.         }  
  61.   
  62.         // schedule the specific windows service to reboot at specific time  
  63.         // every day  
  64.         rebootEveryDayTime(date, servName);  
  65.   
  66.         // add shutdown hook to recover system.out to console when program exits  
  67.         Runtime.getRuntime().addShutdownHook(new Thread() {  
  68.             @Override  
  69.             public void run() {  
  70.                 System.setOut(console);  
  71.             }  
  72.         });  
  73.     }  
  74.   
  75.     private static void rebootEveryDayTime(Date date, final String servName) {  
  76.         new Timer().schedule(new TimerTask() {  
  77.             public void run() {  
  78.                 try {  
  79.                     reboot(servName);  
  80.                 } catch (Exception e) {  
  81.                     LOG("重启出现异常:" + e.getMessage());  
  82.                 }  
  83.             }  
  84.         }, date, 24 * 60 * 60 * 1000);  
  85.     }  
  86.   
  87.     private static void reboot(String servName) throws IOException, InterruptedException {  
  88.         LOG("重启服务:" + servName);  
  89.         Process procStop;  
  90.         Process procStart;  
  91.         int stopState = -1;  
  92.         int startState = -1;  
  93.   
  94.         // stop the specific service  
  95.         procStop = Runtime.getRuntime().exec("net stop \"" + servName + "\"");  
  96.   
  97.         stopState = getProcExecStat(procStop);  
  98.         LOG(getProcOutput(procStop));  
  99.   
  100.         // wait for 10 seconds   
  101.         try {  
  102.             Thread.sleep(10 * 1000);  
  103.         } catch (InterruptedException e) {  
  104.             LOG("线程等待时中断...");  
  105.             e.printStackTrace();  
  106.         }  
  107.   
  108.         // restart  
  109.         procStart=Runtime.getRuntime().exec("net start \"" + servName + "\"");  
  110.         startState = getProcExecStat(procStart);  
  111.         LOG(getProcOutput(procStart));  
  112.   
  113.         //if stop exec and start exec both return with failed flag,exists  
  114.         if (stopState != 0 && startState != 0) {  
  115.             LOG("重启失败,请确认服务名是否有效,程序将退出...");  
  116.         } else {  
  117.             LOG("重启成功.");  
  118.         }  
  119.     }  
  120.   
  121.     private static int getProcExecStat(Process proc) {  
  122.         try {  
  123.             return proc.waitFor();  
  124.         } catch (InterruptedException e) {  
  125.             LOG("线程等待时中断...");  
  126.             e.printStackTrace();  
  127.         }  
  128.         return -1;  
  129.     }  
  130.   
  131.     private static String getProcOutput(Process proc) throws IOException, InterruptedException {  
  132.         InputStream is = proc.getInputStream();  
  133.         String line;  
  134.         StringBuffer strResult = new StringBuffer();  
  135.   
  136.         BufferedReader reader = new BufferedReader(new InputStreamReader(is));  
  137.         while ((line = reader.readLine()) != null) {  
  138.             strResult.append(line);  
  139.         }  
  140.         is.close();  
  141.          
  142.         return strResult.toString().trim();  
  143.     }  
  144.   
  145.     private static void LOG(String info) {  
  146.         if (info != null && !info.equals("")) {  
  147.             System.out.println("windows服务监控器--------" + getCurrentTime() + "----------->" + info);  
  148.         }  
  149.     }  
  150.   
  151.     private static String getCurrentTime() {  
  152.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
  153.         return sdf.format(new Date());  
  154.     }  
  155.   
  156.     // public enum ExecuteStates {  
  157.     //  
  158.     // SUCCEED(0, ""), STATERR_STOPPED(1, "服务已停止"), STATERR_STATED(3, "服务已开始"),  
  159.     // STATERR_NOTFOUND(  
  160.     // 2, "服务名无效");  
  161.     //  
  162.     // ExecuteStates(int code, String desc) {  
  163.     // this.code = code;  
  164.     // this.desc = desc;  
  165.     // }  
  166.     //  
  167.     // private final int code;  
  168.     // private final String desc;  
  169.     //  
  170.     // // regular get method  
  171.     // public String getDesc() {  
  172.     // return desc;  
  173.     // }  
  174.     //  
  175.     // public static String getDescByCode(int code){  
  176.     // for (ExecuteStates e:ExecuteStates.values()){  
  177.     // if(e.code==code){  
  178.     // return e.desc;  
  179.     // }  
  180.     // }  
  181.     // return null;  
  182.     // }  
  183.     // }  
  184.   
  185. }  
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP