yuanxueming 发表于 2015-05-26 14:32

Java实现定时重启windows指定服务

package com.test.processManagement;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
* <title>ServRebootScheWin</title>
*
* <project>Exam</project>
*
* <package>com.test.processManagement</package>
*
* <file>ServRebootScheWin.java</file>
*
* <date>2012-7-11</date>
*
* <brief>本程序用于每天定时重启windows系统上的指定服务,并记录日志</brief>
*
* @author Wero
*
*/
public class ServRebootScheWin {

    public static void main(String[] args) {
      // store the console output
      final PrintStream console = System.out;
      if (args.length < 2) {
            LOG("参数不全,程序将退出...");
            Runtime.getRuntime().exit(-1);
      }

      final String timeStr = args;// 每天重启时间(HH:mm:ss)
      final String servName = args;// 服务名
      if (args.length >= 3) {
            try {
                System.setOut(new PrintStream(new FileOutputStream(args)));
            } catch (FileNotFoundException e) {
                System.setOut(console);
                LOG("日志文件无法建立...");
            }
      }

      // convert time string to Date type
      Date date = null;
      try {
            date = new SimpleDateFormat("HH:mm:ss").parse(timeStr);
      } catch (ParseException e1) {
            LOG("日期格式(HH:mm:ss)错误,程序将退出...");
            Runtime.getRuntime().exit(-1);
      }

      // schedule the specific windows service to reboot at specific time
      // every day
      rebootEveryDayTime(date, servName);

      // add shutdown hook to recover system.out to console when program exits
      Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.setOut(console);
            }
      });
    }

    private static void rebootEveryDayTime(Date date, final String servName) {
      new Timer().schedule(new TimerTask() {
            public void run() {
                try {
                  reboot(servName);
                } catch (Exception e) {
                  LOG("重启出现异常:" + e.getMessage());
                }
            }
      }, date, 24 * 60 * 60 * 1000);
    }

    private static void reboot(String servName) throws IOException, InterruptedException {
      LOG("重启服务:" + servName);
      Process procStop;
      Process procStart;
      int stopState = -1;
      int startState = -1;

      // stop the specific service
      procStop = Runtime.getRuntime().exec("net stop \"" + servName + "\"");

      stopState = getProcExecStat(procStop);
      LOG(getProcOutput(procStop));

      // wait for 10 seconds   
      try {
            Thread.sleep(10 * 1000);
      } catch (InterruptedException e) {
            LOG("线程等待时中断...");
            e.printStackTrace();
      }

      // restart
      procStart=Runtime.getRuntime().exec("net start \"" + servName + "\"");
      startState = getProcExecStat(procStart);
      LOG(getProcOutput(procStart));

      //if stop exec and start exec both return with failed flag,exists
      if (stopState != 0 && startState != 0) {
            LOG("重启失败,请确认服务名是否有效,程序将退出...");
      } else {
            LOG("重启成功.");
      }
    }

    private static int getProcExecStat(Process proc) {
      try {
            return proc.waitFor();
      } catch (InterruptedException e) {
            LOG("线程等待时中断...");
            e.printStackTrace();
      }
      return -1;
    }

    private static String getProcOutput(Process proc) throws IOException, InterruptedException {
      InputStream is = proc.getInputStream();
      String line;
      StringBuffer strResult = new StringBuffer();

      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      while ((line = reader.readLine()) != null) {
            strResult.append(line);
      }
      is.close();
         
      return strResult.toString().trim();
    }

    private static void LOG(String info) {
      if (info != null && !info.equals("")) {
            System.out.println("windows服务监控器--------" + getCurrentTime() + "----------->" + info);
      }
    }

    private static String getCurrentTime() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      return sdf.format(new Date());
    }

    // public enum ExecuteStates {
    //
    // SUCCEED(0, ""), STATERR_STOPPED(1, "服务已停止"), STATERR_STATED(3, "服务已开始"),
    // STATERR_NOTFOUND(
    // 2, "服务名无效");
    //
    // ExecuteStates(int code, String desc) {
    // this.code = code;
    // this.desc = desc;
    // }
    //
    // private final int code;
    // private final String desc;
    //
    // // regular get method
    // public String getDesc() {
    // return desc;
    // }
    //
    // public static String getDescByCode(int code){
    // for (ExecuteStates e:ExecuteStates.values()){
    // if(e.code==code){
    // return e.desc;
    // }
    // }
    // return null;
    // }
    // }

}
页: [1]
查看完整版本: Java实现定时重启windows指定服务