2015-05-21 100 views
-4

我需要創建一個帶有多個定時器和定時器號碼的Windows服務不能貶值。幾乎40個計時器需要創建。這是可能的動態計時器。所需定時器的數量將從DB加載。建議創建動態計時器嗎?如果是,我們可以在Windows服務中創建動態計時器嗎?我們是否可以創建多個動態定時器

回答

1

嘗試是這樣的:

public static class AppTimer 
{ 
    static AppTimer() 
    { 
     Events = new Dictionary<string, Event>(); 
    } 

    public static Dictionary<string, Event> Events { get; set; } 

    public static void AddEvent(string eventType, Event newEvent) 
    { 
     if (Events.ContainsKey(eventType)) 
     { 
      Events[eventType].Timer.Stop(); 
      Events[eventType] = null; 
      Events.Remove(eventType); 
     } 

     Events.Add(eventType, newEvent); 
    } 

    private static int CalculateTimerInterval(int minute) 
    { 
     if (minute < 0) minute = 60; 

     var now = DateTime.Now; 

     var future = new DateTime(); 

     // We want to run right away 
     if (minute == 0) 
     { 
      future = now.AddSeconds(1.5); 
     } 
     else 
     { 
      future = now.AddMinutes((minute - (now.Minute%minute))) 
       .AddSeconds(now.Second*-1) 
       .AddMilliseconds(now.Millisecond*-1); 
     } 

     var interval = future - now; 

     return (int)interval.TotalMilliseconds; 
    } 

    public class Event 
    { 
     public Event(Action tick, int interval) 
     { 
      this.Timer = new Timer { Interval = CalculateTimerInterval(interval) }; 
      this.Timer.AutoReset = false; 
      this.Timer.Elapsed += (sender, args) => 
      { 
        tick?.Invoke(); 

       if (this.Interval > 0) 
       { 
        this.Timer.Interval = CalculateTimerInterval(this.Interval); 
       } 
      }; 
      this.Interval = interval; 
      this.Timer.Start(); 
     } 

     public Timer Timer { get; set; } 

     public int Interval { get; set; } 

     public void ChangeInterval(int newInterval) 
     { 
      this.Interval = newInterval; 
      this.Timer.Interval = CalculateTimerInterval(newInterval); 
     } 
    } 
} 

使用示例:

AppTimer.AddEvent("My Task #1", new AppTimer.Event(()=> { Console.WriteLine("Event Fired"); }, 1)); 
+1

僅供參考,VS 2015和C#6不公開發布還,所以用'.'操作ISN」?完全猶太教。 – Cameron

相關問題