TimerManager.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using Common.Helper;
  4. using MongoDB.Bson;
  5. namespace Common.Base
  6. {
  7. public class TimerManager
  8. {
  9. private class Timer
  10. {
  11. public ObjectId Id { get; set; }
  12. public long Time { get; set; }
  13. public Action Action { get; set; }
  14. }
  15. private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
  16. /// <summary>
  17. /// key: time, value: timer id
  18. /// </summary>
  19. private readonly MultiMap<long, ObjectId> timeGuid = new MultiMap<long, ObjectId>();
  20. private readonly Queue<long> timeoutTimer = new Queue<long>();
  21. public ObjectId Add(long time, Action action)
  22. {
  23. Timer timer = new Timer { Id = ObjectId.GenerateNewId(), Time = time, Action = action };
  24. this.timers[timer.Id] = timer;
  25. this.timeGuid.Add(timer.Time, timer.Id);
  26. return timer.Id;
  27. }
  28. public void Remove(ObjectId id)
  29. {
  30. Timer timer;
  31. if (!this.timers.TryGetValue(id, out timer))
  32. {
  33. return;
  34. }
  35. this.timers.Remove(timer.Id);
  36. this.timeGuid.Remove(timer.Time, timer.Id);
  37. }
  38. public void Refresh()
  39. {
  40. long timeNow = TimeHelper.Now();
  41. foreach (long time in this.timeGuid.Keys)
  42. {
  43. if (time > timeNow)
  44. {
  45. break;
  46. }
  47. this.timeoutTimer.Enqueue(time);
  48. }
  49. while (this.timeoutTimer.Count > 0)
  50. {
  51. long key = this.timeoutTimer.Dequeue();
  52. ObjectId[] timeoutIds = this.timeGuid.GetAll(key);
  53. foreach (ObjectId id in timeoutIds)
  54. {
  55. Timer timer;
  56. if (!this.timers.TryGetValue(id, out timer))
  57. {
  58. continue;
  59. }
  60. this.Remove(id);
  61. timer.Action();
  62. }
  63. }
  64. }
  65. }
  66. }