2014-02-14 2 views
0

다음은 응용 프로그램을 다시 시작하려고 시도하는 프로그램의 코드입니다. 나는 그것이 작동하도록 여러 가지 방법을 시도하고, "목록"에 대한 Google과 Stackoverflow를 연구했지만, 나는 이해하지 못하거나 내가 원하는 것을 얻지 못하고있다. "RestartData"는 속성을 저장하는 .cs 파일이며 program.cs는 프로그램의 유일한 다른 부분입니다. 이것은 주요 부분입니다.C# 목록을 처리하는 방법

문제 영역은 proecessRestartList 함수입니다. 목록 (foreach)을 살펴보고 LastRestartTime이 무엇인지 확인하고 RestartInterval보다 클 경우 프로세스를 종료하고 다시 시작합니다. 내 문제는 실제로 processRestartList 함수를 만들기 위해 실제로 구문을 작성하는 방법을 알지 못합니다. 모든 도움이 크게 감사 할 것입니다. RestarInterval에 대한

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

설정되어 무엇이든 TimeSpan''로'RestartInterval'을하는 것이 좋을 것이라고 큰 경우 확인하고 싶습니다. '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

단위는 명확하지 않다, 그래서 나는 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. (...')를 사용하기를 원할 수도 있습니다 (이것은 포스터에서가 아니라 미래의 독자에게 더 지시됩니다. 대답) –

관련 문제