2013-10-11 36 views
0

我正在創建一個Windows服務,它控制一堆其他進程,但需要內部進程運行到自己的計劃。 每個日程安排都相對簡單,只需選擇一週中的哪幾天運行,何時應該啓動以及何時應該停止。如何排序多維詞典的內部價值

我的想法是有多方面的字典,如下面

Dictionary<string, TimeSpan> OnOff = new Dictionary<string,TimeSpan>(); 
OnOff.Add("Start", TimeSpan.Parse("09:00")); 
OnOff.Add("Stop", TimeSpan.Parse("17:00")); 

Dictionary<string, Dictionary<string, TimeSpan>> Process = new Dictionary<string,Dictionary<string,TimeSpan>>(); 
Process.Add("Process1", OnOff); 

Dictionary<DayOfWeek, Dictionary<string, Dictionary<string, TimeSpan>>> schedule = new Dictionary<DayOfWeek,Dictionary<string,Dictionary<string,TimeSpan>>>(); 
schedule.Add(DayOfWeek.Monday, Process); 

並進行排序由最近的「開關機」的時間跨度的「過程」字典使用一個簡單的定時器作用於下一個動作之前用於TimeSpan到達時的過程。

我對這個計劃的問題是TimeSpans的排序,並找到哪個「開始」/「停止」操作包含最接近的TimeSpan進行排序。此外,它可能是包含最接近的TimeSpan的每個流程的不同操作。

或者任何人都可以想到一個簡單的方法來實現相同類型的結果嗎?

回答

0

由於結構日程安排信息總是存在於App.Config文件中我決定我不需要將它存儲在其他地方。 我處理調度的方式是找到所有需要在最近的將來採取行動的流程,並且只存儲這些流程細節,調度時間和所需的操作。

然後,我只需運行一個計時器,並在計劃時間執行開始或停止操作。 一旦處理了所有這些進程,我再次查看App.Config並找到了要處理的下一個進程列表。

// The method that will be called when the schedule thread is started 
    private void ProcessSchedule() 
    { 
     Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); 

     // work out the length of time between now and the schedule time 
     string today = DateTime.Now.ToString("dd.MM.yyy"); 
     DateTime abaseTime = Convert.ToDateTime(today); 
     TimeSpan scheduleTime = schedules.First().Value.ActionTime; 
     DateTime actionTime = abaseTime.Add(scheduleTime); 


     // log the schedule is starting 
     if (log.IsInfoEnabled) log.Info(String.Format("Schedule created. Next action will take place at {0}", actionTime.ToString())); 

     while (Running) 
     { 
      // this kills this process 
      if (threadStop.WaitOne(0)) 
      { 
       if (log.IsInfoEnabled) log.Info(String.Format("Schedules cancelled")); 
       break; 
      } 

      if (DateTime.Now < actionTime) 
      { 
       //sleep 5 seconds before checking again. If we go any longer we keep our service from shutting down when it needs to. 
       threadStop.WaitOne(5000); 
       continue; 
      } 

      // tell the service control that it can action the schedules now 
      ServiceControl.actionSchedule.Set(); 

      break; 
     } 


    } 
0

爲什麼不保持結構

`class ProcessInfo 
{ 
String ProcessID; 
TimeSpan startTime; 
TimeSpan endTime; 
}` 

,並保持字典簡單 Dictionary<string,ProcessInfo> schedule = new Dictionary<string,ProcessInfo>(); 剛剛創建的processinfo一個新的對象,當你需要添加到列表

+0

我很欣賞有不同的方式來存儲數據 - 如在類/結構,但存在的問題仍然不必爲星期幾的數據和賬戶進行排序的。 – David

+0

您可以定期運行排序函數/算法,並將進程存儲在索引中運行 – Moiz

+0

對不起,它只是發生在我身上,而不是僅僅保留ProcessInfo,您應該保留processInfo的**數組**,並且如果要按類型排序數組使用簡單的排序算法。 – Moiz