| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- using System.Collections.Generic;
- using Common.Base;
- using Common.Event;
- using Common.Helper;
- using MongoDB.Bson;
- namespace Model
- {
- public class TimerComponent : Component<World>, IRunner
- {
- private class Timer
- {
- public ObjectId Id { get; set; }
- public long Time { get; set; }
- public int CallbackId { get; set; }
- public Env Env { get; set; }
- }
- private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
- /// <summary>
- /// key: time, value: timer id
- /// </summary>
- private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
- private readonly Queue<long> timeoutTimer = new Queue<long>();
- public ObjectId Add(long time, int callbackId, Env env)
- {
- Timer timer = new Timer
- {
- Id = ObjectId.GenerateNewId(),
- Time = time,
- CallbackId = callbackId,
- Env = env
- };
- this.timers[timer.Id] = timer;
- this.timeId.Add(timer.Time, timer.Id);
- return timer.Id;
- }
- public void Remove(ObjectId id)
- {
- Timer timer;
- if (!this.timers.TryGetValue(id, out timer))
- {
- return;
- }
- this.timeId.Remove(timer.Time, timer.Id);
- }
- public void Run()
- {
- long timeNow = TimeHelper.Now();
- foreach (long time in this.timeId.Keys)
- {
- if (time > timeNow)
- {
- break;
- }
- timeoutTimer.Enqueue(time);
- }
- while (timeoutTimer.Count > 0)
- {
- long key = timeoutTimer.Dequeue();
- List<ObjectId> timeOutId = this.timeId[key];
- foreach (ObjectId id in timeOutId)
- {
- Timer timer;
- if (!this.timers.TryGetValue(id, out timer))
- {
- continue;
- }
- this.Remove(id);
- World.Instance.GetComponent<EventComponent<ActionAttribute>>()
- .Run(timer.CallbackId, timer.Env);
- }
- }
- }
- }
- }
|