TimerComponent.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Collections.Generic;
  2. using Common.Base;
  3. using Common.Event;
  4. using Common.Helper;
  5. using MongoDB.Bson;
  6. namespace Model
  7. {
  8. public class TimerComponent : Component<World>, IRunner
  9. {
  10. private class Timer
  11. {
  12. public ObjectId Id { get; set; }
  13. public long Time { get; set; }
  14. public int CallbackId { get; set; }
  15. public Env Env { get; set; }
  16. }
  17. private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
  18. /// <summary>
  19. /// key: time, value: timer id
  20. /// </summary>
  21. private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
  22. private readonly Queue<long> timeoutTimer = new Queue<long>();
  23. public ObjectId Add(long time, int callbackId, Env env)
  24. {
  25. Timer timer = new Timer
  26. {
  27. Id = ObjectId.GenerateNewId(),
  28. Time = time,
  29. CallbackId = callbackId,
  30. Env = env
  31. };
  32. this.timers[timer.Id] = timer;
  33. this.timeId.Add(timer.Time, timer.Id);
  34. return timer.Id;
  35. }
  36. public void Remove(ObjectId id)
  37. {
  38. Timer timer;
  39. if (!this.timers.TryGetValue(id, out timer))
  40. {
  41. return;
  42. }
  43. this.timeId.Remove(timer.Time, timer.Id);
  44. }
  45. public void Run()
  46. {
  47. long timeNow = TimeHelper.Now();
  48. foreach (long time in this.timeId.Keys)
  49. {
  50. if (time > timeNow)
  51. {
  52. break;
  53. }
  54. timeoutTimer.Enqueue(time);
  55. }
  56. while (timeoutTimer.Count > 0)
  57. {
  58. long key = timeoutTimer.Dequeue();
  59. List<ObjectId> timeOutId = this.timeId[key];
  60. foreach (ObjectId id in timeOutId)
  61. {
  62. Timer timer;
  63. if (!this.timers.TryGetValue(id, out timer))
  64. {
  65. continue;
  66. }
  67. this.Remove(id);
  68. World.Instance.GetComponent<EventComponent<ActionAttribute>>()
  69. .Run(timer.CallbackId, timer.Env);
  70. }
  71. }
  72. }
  73. }
  74. }