2014-02-14 65 views
0

下面是我嘗試創建的程序的代碼以重新啓動應用程序。我已經嘗試了幾種不同的方法來使它工作,研究谷歌和Stackoverflow關於「列表」,但我要麼不理解,要麼得不到我需要的東西。 「RestartData」是存儲屬性的.cs文件,program.cs是該程序的唯一其他部分。這是主要部分。C#如何處理列表

的問題領域我是在proecessRestartList功能。我想通過列表(foreach)並查看LastRestartTime是什麼,如果它大於RestartInterval,則終止進程並重新啓動它。我的問題是不確定如何實際編寫語法以使函數processRestartList實際執行該操作。任何和所有的幫助將不勝感激。

class RestartData 
    { 
     public string ProgramLocation { get; set; } 
     public bool Active { get; set; } 
     public int RestarInterval { get; set; } 
     public bool RestartIfRunning { get; set; } 
     public string ProgramServer { get; set; } 
     public string ProcessName { get; set; } 
     public DateTime LastRestartTime { get; set; } 
    } 

namespace ApplicationWatcher 
    { 
     public class RestartApplicationTask 
     { 
      public Int32 SleepInterval { get; set; } 
      public String Status { get; set; } 
      public String Error { get; set; } 
      public bool Stopping { get; set; } 
      public static log4net.ILog log { get; set; } 

     public void Start() 
     { 
      Stopping = false; 
      Error = ""; 
      Status = "Starting"; 
      if (SleepInterval == 0) 
      { 
       SleepInterval = 3600; 
      } 

      //make sure there is a logger 
      if (log == null) 
      { 
       log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["log4net"]))); 

       log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 
      } 


      //This calls a method within the class. The name of the class is not needed, but the list and name of list is needed. 
      List<RestartData> restartWorkList = AppRestartList(); 

      try 
      { 
       processRestartList(restartWorkList); 
      } 
      catch (Exception e) 
      { 
       //Replace with logging 
       log.Info("Error: could not process " + restartWorkList); 
      } 
     } 

     public static Happy.Common.HappyTools.DB GetCurrentlyRunningApplications(bool Active) 
     { 

     String qry= "SELECT ProgramLocation, Active, RestartIfRunning FROM any_database.dbo.AppWatcher WITH (NOLOCK) WHERE Active = 1"; 
     //qry = qry.Replace("<Active>", Active.ToString()); 
     SqlCommand cmd = new SqlCommand(qry, (SqlConnection)DB.MakeConnection("any_database")); 
     DataTable dt; 

     Happy.Common.HappyTools.DB returnValue = new Happy.Common.HappyTools.DB(); 
     try 
     { 
      dt = DB.ExecuteTable(cmd, "any_database"); 

      DataRow thisRow = dt.Rows[0]; 
     } 
     catch (Exception e) 
     { 
      //do something 
     } 
     finally { } 
     return returnValue; 
     } 

     static List<RestartData> AppRestartList() 
     { 
      List<RestartData> restartDatas = new List<RestartData>(); 

      //Don't need to create a new instance but does need to be assigned to at least null 
      RestartData restartData = null; 

      //This is an actual SQL Query that would be the same as in a SQL manager. 
      string sqlQuery = "Select RestartTime, ProgramLocation, LastRestartTime, RestartInterval, ProgramServer, RestartIfRunning, ProcessName from dbo.AppWatcher where active=1;"; 

      //execute sql query 
      //execute database reader 
      SqlCommand command = new SqlCommand(sqlQuery, (SqlConnection)DB.MakeConnection("any_database")); 
      DataTable dt; 



      command.Connection.Open(); 

      dt = DB.ExecuteTable(command, "any_database"); 

      foreach (DataRow row in dt.Rows) 
      { 
       //move stuff from reader into log data, and exp 
       //not RestartData restartData = new RestartData(); The RestartData() method is already declared 
       restartData = new RestartData(); 
       restartData.ProgramLocation = Misc.NullSafeString(row["programLocation"]); 
       //restartData.Active = Misc.NullSafeBool(row["active"]); 
       restartData.RestarInterval = Misc.NullSafeInt(row["restartInterval"]); 
       restartData.RestartIfRunning = Misc.NullSafeBool(row["restartIfRunning"]); 
       restartData.ProcessName = Misc.NullSafeString(row["processName"]); 
       restartData.LastRestartTime = Misc.NullSafeDateTime(row["lastRestartTime"]); 

       //add restartData to list 
       restartDatas.Add(restartData); 

      } 
      return restartDatas; 
     } 

     static void processRestartList(List<RestartData>restartJob) 
     {  


      //i represents all the properties in LogData 
      **foreach(RestartData i in restartJob) 
      { 
       if (i <= RestartData()) 
       { 
        i.LastRestartTime.AddHours(-1); 
       } 

      }** 
     }  
    } 
} 
+0

我只是想通過列表進行迭代,並檢查LastRestartTime更大,無論它被設置爲 – webby68

+0

這將是很好做'RestartInterval'爲'TimeSpan'。你可以做'TimeSpan.FromSeconds(someNumber)'這樣的事情來輕鬆創建特定單元的時間間隔。 –

回答

1

你想要下面的東西。假設RestartInterval代表小時。

// Check what LastRestartTime is and if it is greater that RestartInterval, kill the process and restart it. 
DateTime dt = DateTime.Now; // Keep DateTime static. 
foreach(RestartData restartData in restartJob) 
{ 
    if (dt >= restartData.LastRestartTime.AddHours(restartData.RestarInterval)) 
    { 
     restartData.LastRestartTime = dt; 
     // restart process 
    } 
} 
+1

請參閱[我對LB的回答的評論](http://stackoverflow.com/questions/21788602/c-sharp-how-to-process-a-list#comment32966943_21788738)關於事情實施者應該知道的當在循環中使用'DateTime.Now'時 –

+0

謝謝,這讓我走上了正確的道路,我只是不確定如何做到這一點 – webby68

+0

我已經刪除了減號,因爲我的邏輯混淆了。 @ScottChamberlain編輯。 –

1

單位爲RestarInterval不清楚,所以我假設seconds。如果它不同,請相應地更改TotalSeconds(TotalMinutes,TotalHours等)。

foreach(var data in restartJob.Where(x=> DateTime.Now.Subtract(x.LastRestartTime).TotalSeconds > x.RestarInterval)) 
{ 
    //kill 
} 
+1

在foreach循環中有'DateTime.Now'有一些你需要知道的副作用。在處理項目時,你將要比較的時間將「隨你移動」,對於像這樣的快速循環可能無關緊要,但如果這用於需要很長時間處理的循環,這取決於你的行爲希望你可能想把它移到循環外部var now = DateTime.Now,並在循環中使用now.Subtract。(...)(這是針對未來的讀者,而不是在答案) –