Timer.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. namespace BestHTTP.Extensions
  4. {
  5. public
  6. #if CSHARP_7_OR_LATER
  7. readonly
  8. #endif
  9. struct TimerData
  10. {
  11. public readonly DateTime Created;
  12. public readonly TimeSpan Interval;
  13. public readonly object Context;
  14. public readonly Func<DateTime, object, bool> OnTimer;
  15. public bool IsOnTime(DateTime now)
  16. {
  17. return now >= this.Created + this.Interval;
  18. }
  19. public TimerData(TimeSpan interval, object context, Func<DateTime, object, bool> onTimer)
  20. {
  21. this.Created = DateTime.Now;
  22. this.Interval = interval;
  23. this.Context = context;
  24. this.OnTimer = onTimer;
  25. }
  26. /// <summary>
  27. /// Create a new TimerData but the Created field will be set to the current time.
  28. /// </summary>
  29. public TimerData CreateNew()
  30. {
  31. return new TimerData(this.Interval, this.Context, this.OnTimer);
  32. }
  33. public override string ToString()
  34. {
  35. return string.Format("[TimerData Created: {0}, Interval: {1}, IsOnTime: {2}]", this.Created.ToString(System.Globalization.CultureInfo.InvariantCulture), this.Interval, this.IsOnTime(DateTime.Now));
  36. }
  37. }
  38. public static class Timer
  39. {
  40. private static List<TimerData> Timers = new List<TimerData>();
  41. public static void Add(TimerData timer)
  42. {
  43. Timers.Add(timer);
  44. }
  45. internal static void Process()
  46. {
  47. if (Timers.Count == 0)
  48. return;
  49. DateTime now = DateTime.Now;
  50. for (int i = 0; i < Timers.Count; ++i)
  51. {
  52. TimerData timer = Timers[i];
  53. if (timer.IsOnTime(now))
  54. {
  55. bool repeat = timer.OnTimer(now, timer.Context);
  56. if (repeat)
  57. Timers[i] = timer.CreateNew();
  58. else
  59. Timers.RemoveAt(i--);
  60. }
  61. }
  62. }
  63. }
  64. }