2010年10月6日 星期三

檢查service是否執行

檢查service是否執行,如未執行則執行之 程式碼參考以下網站 http://blog.miniasp.com/post/2009/04/Windows-Service-Start-Stop-Restart-in-CSharp.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
namespace auto_services
{
  class Program
  {
    class APP
    {
      //start_serv returns
      //return 1 work start
      //return 0 work fault
      public static int start_serv(string m_ServiceName)
      {
        try
        {
          // 建立 ServiceController 物件實體
          ServiceController service = new ServiceController(m_ServiceName);
          // 設定一個 Timeout 時間,若超過 30 秒啟動不成功就宣告失敗!                      
          TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 30);
          // 啟動服務                      
          service.Start();
          // 設定該服務必須在等待 timeout 時間內將狀態改變至「已啟動(Running)」的狀態
          service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }                
        catch                
        {                    
          return 0;                
        }                
          return 1;
      }            
      //status_serv returns            
      //return 1 work            
      //return 0 stop            
      public static int status_serv(string m_ServiceName)            
      {                
        // 建立 ServiceController 物件實體                  
        ServiceController service = new ServiceController(m_ServiceName);
        if (service.Status != ServiceControllerStatus.Stopped && service.Status != ServiceControllerStatus.StopPending)
          return 1;                
        else                    
          return 0;            
      }            
      public static void run_serv(string m_ServiceName)            
      {                
        if (APP.status_serv(m_ServiceName) == 0)                
        {                    
          int i = APP.start_serv(m_ServiceName);                    
          if (i == 1)                        
            Console.WriteLine(m_ServiceName + "服務成功啟動!");                    
          else                        
            Console.WriteLine(m_ServiceName + "服務無法啟動,請檢查相關設定!");                
        }                
        else                
        {                    
          Console.WriteLine(m_ServiceName + "服務已啟動!");                
        }            
      }        
    }
        static void Main(string[] args)
        {            
      // 已知的 Service Name              
      string m_ServiceName = "MSSQL";            
      //檢查並執行             
      APP.run_serv(m_ServiceName);        
    }    
  }
}

沒有留言: