feat(timers): Adds timer pooling, fixes timer related bugs, and changes timer api (#667)

### Changes/Fixes:
* Adds timer pooling.
* Allows pool to be configurable in ModernUO.json
* Pool replenishes itself asynchronously if depleted.
* Fixes an issue with barkeeps and town criers
* Fixes an issue with incognito buff icons not being removed
* Fixes an issue with polymorph name mod not being removed
* Fixes several places where timers go on forever even after an object is deleted, keeping a reference (memory leak)
* Eliminates the timer for MiningCart altogether.
* Deletes `AcidSlime` since it is a duplicate of `PoolOfAcid`
* Fixes HonorableExecution and standardizes the code for other Bushido moves.

## Changes to the Timer API:
```cs
public class Timer
{
  // Creates a timer that will be returned to the pool once execution stops.
  public static void StartTimer(Action callback);
  public static void StartTimer(TimeSpan delay, Action callback);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback);
  public static void StartTimer(TimeSpan interval, int count, Action callback);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback);

  // Creates a timer and returns a token for more control. Requires manual cancellation in order for the timer to be returned to the pool.
  // If the token is dereferenced, the timer will be dereferenced too. While not returning a timer to the pool is not considered hazardous, it does defeat the purpose of pooled timers.
  public static void StartTimer(Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan interval, int count, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback, out TimerExecutionToken token);

  // If you aren't sure how to use the API above, or you don't care about performance, then you can use the old RunUO Timer.DelayCall
  public static DelayCallTimer DelayCall(Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan interval, int count, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, int count, Action callback);
}

public struct TimerExecutionToken
{
  public bool Running { get; }
  public int Index { get; }
  public int RemainingCount { get; }
  public DateTime Next { get; }
}
```

## When to use `TimerExecutionToken`?
Use tokens when you want to gain the performance benefit of using a pooled timer, but you need one of the following:
* Access to the next time the timer will tick:`token.Next`
* Access to which interval, how many intervals there are, or how many are remaining: `token.Index`, `token.Count`, and `token.RemainingCount`
* Stop a timer manually.
* Determine if the timer is running: `timer.Running`
* See notes below about requirements for using tokens!

## Notes about using the TimerExecutionToken:
When you opt-in to receive a token, you must call `Cancel()` to return the timer. This can be done inside of the callback, or outside of the callback at any time.
If this is not called and your timer is an infinite interval, then you will create a potential memory leak, or null pointer exception in your callback.
If the timer ends and is stopped, but cancel is not called, then the timer will never return to the pool and stay referenced until the token is deleted or cancel is called. (Memory leak)

## Is this thread safe?
No. The ModernUO timer system is not thread safe at all. If you require a thread safe timer system, contact me and I'll help adapt this system. Keep in mind that there is a massive performance hit to make this thread safe when there are literally no use cases for it.

If you need to synchronize execution, meaning you want to execute code from another thread on the core thread. Let's say you have a discord bot that is pushing commands to the game server. Then use `EventLoopContext.Post(SendOrPostCallback callback, object state);`.
This commit is contained in:
Kamron Batman 2021-08-07 14:33:35 -07:00 • committed by GitHub
parent b4de631f96
commit 9b554f69b0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
219 changed files with 1897 additions and 2241 deletions

View file

@ -1,106 +0,0 @@
using System;
using System.Collections.Generic;
using Server.Mobiles;
namespace Server.Items
{
public class AcidSlime : Item
{
private readonly DateTime m_Created;
private readonly TimeSpan m_Duration;
private readonly int m_MaxDamage;
private readonly int m_MinDamage;
private readonly Timer m_Timer;
private bool m_Drying;
[Constructible]
public AcidSlime() : this(TimeSpan.FromSeconds(10.0), 5, 10)
{
}
[Constructible]
public AcidSlime(TimeSpan duration, int minDamage, int maxDamage)
: base(0x122A)
{
Hue = 0x3F;
Movable = false;
m_MinDamage = minDamage;
m_MaxDamage = maxDamage;
m_Created = Core.Now;
m_Duration = duration;
m_Timer = Timer.DelayCall(TimeSpan.Zero, TimeSpan.FromSeconds(1), OnTick);
}
public AcidSlime(Serial serial) : base(serial)
{
}
public override string DefaultName => "slime";
public override void OnAfterDelete()
{
m_Timer?.Stop();
}
private void OnTick()
{
var now = Core.Now;
var age = now - m_Created;
if (age > m_Duration)
{
Delete();
}
else
{
if (!m_Drying && age > m_Duration - age)
{
m_Drying = true;
ItemID = 0x122B;
}
var toDamage = new List<Mobile>();
foreach (var m in GetMobilesInRange(0))
{
if (m.Alive && !m.IsDeadBondedPet && (!(m is BaseCreature bc) || bc.Controlled || bc.Summoned))
{
toDamage.Add(m);
}
}
for (var i = 0; i < toDamage.Count; i++)
{
Damage(toDamage[i]);
}
}
}
public override bool OnMoveOver(Mobile m)
{
Damage(m);
return true;
}
public void Damage(Mobile m)
{
var damage = Utility.RandomMinMax(m_MinDamage, m_MaxDamage);
if (Core.AOS)
{
AOS.Damage(m, damage, 0, 0, 0, 100, 0);
}
else
{
m.Damage(damage);
}
}
public override void Serialize(IGenericWriter writer)
{
}
public override void Deserialize(IGenericReader reader)
{
}
}
}

View file

@ -104,7 +104,7 @@ namespace Server.Items
to.Damage(1);
Timer.DelayCall(TimeSpan.FromSeconds(2.0), from.EndAction<Bola>);
Timer.StartTimer(TimeSpan.FromSeconds(2.0), from.EndAction<Bola>);
}
private static bool HasFreeHands(Mobile from)
@ -213,7 +213,7 @@ namespace Server.Items
from.Animate(11, 5, 1, true, false, 0);
from.MovingEffect(to, 0x26AC, 10, 0, false, false);
Timer.DelayCall(TimeSpan.FromSeconds(0.5), FinishThrow, from, to);
Timer.StartTimer(TimeSpan.FromSeconds(0.5), () => FinishThrow(from, to));
}
else
{

View file

@ -7,7 +7,7 @@ namespace Server.Items
{
public class DeceitBrazier : Item
{
private Timer m_Timer;
private TimerExecutionToken _timerToken;
[Constructible]
public DeceitBrazier() : base(0xE31)
@ -95,22 +95,21 @@ namespace Server.Items
PublicOverheadMessage(
MessageType.Regular,
0x3B2,
500761
); // Heed this warning well, and use this brazier at your own peril.
500761 // Heed this warning well, and use this brazier at your own peril.
);
_timerToken.Cancel();
}
public override void OnMovement(Mobile m, Point3D oldLocation)
{
if (NextSpawn < Core.Now) // means we haven't spawned anything if the next spawn is below
// means we haven't spawned anything if the next spawn is below
if (NextSpawn < Core.Now &&
Utility.InRange(m.Location, Location, 1) &&
!Utility.InRange(oldLocation, Location, 1) &&
m.Player && !(m.AccessLevel > AccessLevel.Player || m.Hidden) && !_timerToken.Running)
{
if (Utility.InRange(m.Location, Location, 1) && !Utility.InRange(oldLocation, Location, 1) && m.Player &&
!(m.AccessLevel > AccessLevel.Player || m.Hidden))
{
if (m_Timer?.Running != true)
{
m_Timer = Timer.DelayCall(TimeSpan.FromSeconds(2), HeedWarning);
}
}
Timer.StartTimer(TimeSpan.FromSeconds(2), HeedWarning, out _timerToken);
}
base.OnMovement(m, oldLocation);
@ -180,7 +179,7 @@ namespace Server.Items
DoEffect(spawnLoc, map);
Timer.DelayCall(TimeSpan.FromSeconds(1), SummonCreatureToWorld, bc, spawnLoc, map);
Timer.StartTimer(TimeSpan.FromSeconds(1), () => SummonCreatureToWorld(bc, spawnLoc, map));
NextSpawn = Core.Now + NextSpawnDelay;
}

View file

@ -286,24 +286,24 @@ namespace Server.Items
return;
}
if (trigger is Mobile mobile && mobile.Hidden && mobile.AccessLevel > AccessLevel.Player)
if (trigger is Mobile { Hidden: true } mobile && mobile.AccessLevel > AccessLevel.Player)
{
return;
}
if (SoundID > 0)
{
Timer.DelayCall(SoundDelay, PlaySound, trigger);
Timer.StartTimer(SoundDelay, () => PlaySound(trigger));
}
if (Sequence != null)
{
Timer.DelayCall(TriggerDelay, Sequence.DoEffect, trigger);
Timer.StartTimer(TriggerDelay, () => Sequence.DoEffect(trigger));
}
if (EffectType != ECEffectType.None)
{
Timer.DelayCall(EffectDelay, InternalDoEffect, trigger);
Timer.StartTimer(EffectDelay, () => InternalDoEffect(trigger));
}
}

View file

@ -11,7 +11,7 @@ namespace Server.Items
{
private Mobile m_LitBy;
private int m_Ticks;
private Timer m_Timer;
private TimerExecutionToken _timerToken;
private List<Mobile> m_Users;
[Constructible]
@ -55,15 +55,15 @@ namespace Server.Items
return;
}
if (m_Timer == null)
if (_timerToken.Running)
{
m_Timer = Timer.DelayCall(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), OnFirebombTimerTick);
m_LitBy = from;
from.SendLocalizedMessage(1060582); // You light the firebomb. Throw it now!
from.SendLocalizedMessage(1060581); // You've already lit it! Better throw it now!
}
else
{
from.SendLocalizedMessage(1060581); // You've already lit it! Better throw it now!
Timer.StartTimer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), OnFirebombTimerTick, out _timerToken);
m_LitBy = from;
from.SendLocalizedMessage(1060582); // You light the firebomb. Throw it now!
}
m_Users ??= new List<Mobile>();
@ -80,7 +80,7 @@ namespace Server.Items
{
if (Deleted)
{
m_Timer.Stop();
_timerToken.Cancel();
return;
}
@ -158,7 +158,7 @@ namespace Server.Items
new FirebombField(m_LitBy, toDamage).MoveToWorld(Location, Map);
}
m_Timer.Stop();
_timerToken.Cancel();
Delete();
break;
}
@ -172,33 +172,35 @@ namespace Server.Items
return;
}
if (!(obj is IPoint3D p))
if (obj is not IPoint3D p)
{
return;
}
SpellHelper.GetSurfaceTop(ref p);
var loc = new Point3D(p);
var map = Map;
from.RevealingAction();
var to = p as IEntity ?? new Entity(Serial.Zero, new Point3D(p), Map);
var to = p as IEntity ?? new Entity(Serial.Zero, loc, map);
Effects.SendMovingEffect(from, to, ItemID, 7, 0, false, false, Hue);
Timer.DelayCall(TimeSpan.FromSeconds(1.0), FirebombReposition_OnTick, p, Map);
Timer.StartTimer(TimeSpan.FromSeconds(1.0),
() =>
{
if (Deleted)
{
return;
}
MoveToWorld(loc, map);
}
);
Internalize();
}
private void FirebombReposition_OnTick(IPoint3D p, Map map)
{
if (Deleted)
{
return;
}
MoveToWorld(new Point3D(p), map);
}
private class ThrowTarget : Target
{
public ThrowTarget(Firebomb bomb)
@ -219,7 +221,7 @@ namespace Server.Items
private readonly List<Mobile> m_Burning;
private readonly DateTime m_Expire;
private readonly Mobile m_LitBy;
private readonly Timer m_Timer;
private TimerExecutionToken _timerToken;
public FirebombField(Mobile litBy, List<Mobile> toDamage) : base(0x376A)
{
@ -227,7 +229,7 @@ namespace Server.Items
m_LitBy = litBy;
m_Expire = Core.Now + TimeSpan.FromSeconds(10);
m_Burning = toDamage;
m_Timer = Timer.DelayCall(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(1.0), OnFirebombFieldTimerTick);
Timer.StartTimer(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(1.0), OnFirebombFieldTimerTick, out _timerToken);
}
public FirebombField(Serial serial) : base(serial)
@ -266,7 +268,7 @@ namespace Server.Items
{
if (Deleted)
{
m_Timer.Stop();
_timerToken.Cancel();
return;
}
@ -297,7 +299,7 @@ namespace Server.Items
if (Core.Now >= m_Expire)
{
m_Timer.Stop();
_timerToken.Cancel();
Delete();
}
}

View file

@ -37,10 +37,10 @@ namespace Server.Items
Effects.PlaySound(GetWorldLocation(), Map, 0x387);
Timer.DelayCall(TimeSpan.FromSeconds(0.25), Down1);
Timer.DelayCall(TimeSpan.FromSeconds(0.50), Down2);
Timer.StartTimer(TimeSpan.FromSeconds(0.25), Down1);
Timer.StartTimer(TimeSpan.FromSeconds(0.50), Down2);
Timer.DelayCall(TimeSpan.FromSeconds(5.00), BackUp);
Timer.StartTimer(TimeSpan.FromSeconds(5.00), BackUp);
m_NextUse = Core.Now + TimeSpan.FromSeconds(10.0);
}

View file

@ -139,7 +139,7 @@ namespace Server.Items
}
}
Timer.DelayCall(Refresh);
Timer.StartTimer(Refresh);
}
}
}

View file

@ -4,13 +4,14 @@ using Server.Mobiles;
namespace Server.Items
{
[TypeAlias("Server.Items.AcidSlime")]
public class PoolOfAcid : Item
{
private readonly DateTime m_Created;
private readonly TimeSpan m_Duration;
private readonly int m_MaxDamage;
private readonly int m_MinDamage;
private readonly Timer m_Timer;
private TimerExecutionToken _timerToken;
private bool m_Drying;
[Constructible]
@ -30,7 +31,7 @@ namespace Server.Items
m_Created = Core.Now;
m_Duration = duration;
m_Timer = Timer.DelayCall(TimeSpan.Zero, TimeSpan.FromSeconds(1), OnTick);
Timer.StartTimer(TimeSpan.Zero, TimeSpan.FromSeconds(1), OnTick, out _timerToken);
}
public PoolOfAcid(Serial serial) : base(serial)
@ -39,9 +40,9 @@ namespace Server.Items
public override string DefaultName => "a pool of acid";
public override void OnAfterDelete()
public override void OnDelete()
{
m_Timer?.Stop();
_timerToken.Cancel();
}
private void OnTick()

View file

@ -234,7 +234,7 @@ namespace Server.Items
}
else
{
Timer.DelayCall(m_Delay, DoTeleport, m);
Timer.StartTimer(m_Delay, () => DoTeleport(m));
}
}
@ -454,7 +454,7 @@ namespace Server.Items
);
}
Timer.DelayCall(TimeSpan.FromSeconds(5.0), m.EndAction, this);
Timer.StartTimer(TimeSpan.FromSeconds(5.0), () => m.EndAction(this));
}
return false;
@ -671,7 +671,7 @@ namespace Server.Items
public class WaitTeleporter : KeywordTeleporter
{
private static Dictionary<Mobile, TeleportingInfo> m_Table;
private static Dictionary<Mobile, TeleportingInfo> m_Table = new Dictionary<Mobile, TeleportingInfo>();
[Constructible]
public WaitTeleporter()
@ -700,8 +700,6 @@ namespace Server.Items
public static void Initialize()
{
m_Table = new Dictionary<Mobile, TeleportingInfo>();
EventSink.Logout += EventSink_Logout;
}
@ -709,7 +707,7 @@ namespace Server.Items
{
if (from != null && m_Table.Remove(from, out var info))
{
info.Timer.Stop();
info.TimerToken.Cancel();
}
}
@ -731,11 +729,6 @@ namespace Server.Items
return $"{s} second{(s == 1 ? "" : "s")}";
}
private void EndLock(Mobile m)
{
m.EndAction(this);
}
public override void StartTeleport(Mobile m)
{
if (m_Table.TryGetValue(m, out var info))
@ -755,16 +748,16 @@ namespace Server.Items
if (ShowTimeRemaining)
{
m.SendMessage("Time remaining: {0}", FormatTime(info.Timer.Next - Core.Now));
m.SendMessage("Time remaining: {0}", FormatTime(info.TimerToken.Next - Core.Now));
}
Timer.DelayCall(TimeSpan.FromSeconds(5), EndLock, m);
Timer.StartTimer(TimeSpan.FromSeconds(5), () => m.EndAction(this));
}
return;
}
info.Timer.Stop();
info.TimerToken.Cancel();
}
if (StartMessage != null)
@ -782,7 +775,8 @@ namespace Server.Items
}
else
{
m_Table[m] = new TeleportingInfo(this, Timer.DelayCall(Delay, DoTeleport, m));
Timer.StartTimer(Delay, () => DoTeleport(m), out var timerToken);
m_Table[m] = new TeleportingInfo(this, timerToken);
}
}
@ -821,21 +815,21 @@ namespace Server.Items
private class TeleportingInfo
{
public TeleportingInfo(WaitTeleporter tele, Timer t)
public TeleportingInfo(WaitTeleporter tele, TimerExecutionToken token)
{
Teleporter = tele;
Timer = t;
TimerToken = token;
}
public WaitTeleporter Teleporter { get; }
public Timer Timer { get; }
public TimerExecutionToken TimerToken { get; }
}
}
public class TimeoutTeleporter : Teleporter
{
private Dictionary<Mobile, Timer> m_Teleporting;
private Dictionary<Mobile, TimerExecutionToken> m_Teleporting;
[Constructible]
public TimeoutTeleporter() : this(new Point3D(0, 0, 0))
@ -845,7 +839,7 @@ namespace Server.Items
[Constructible]
public TimeoutTeleporter(Point3D pointDest, Map mapDest = null, bool creatures = false)
: base(pointDest, mapDest, creatures) =>
m_Teleporting = new Dictionary<Mobile, Timer>();
m_Teleporting = new Dictionary<Mobile, TimerExecutionToken>();
public TimeoutTeleporter(Serial serial)
: base(serial)
@ -862,19 +856,16 @@ namespace Server.Items
private void StartTimer(Mobile m, TimeSpan delay)
{
if (m_Teleporting.TryGetValue(m, out var t))
{
t.Stop();
}
m_Teleporting[m] = Timer.DelayCall(delay, StartTeleport, m);
StopTimer(m);
Timer.StartTimer(delay, () => StartTeleport(m), out var timerToken);
m_Teleporting[m] = timerToken;
}
public void StopTimer(Mobile m)
{
if (m_Teleporting.Remove(m, out var t))
{
t.Stop();
t.Cancel();
}
}
@ -923,7 +914,7 @@ namespace Server.Items
var version = reader.ReadInt();
TimeoutDelay = reader.ReadTimeSpan();
m_Teleporting = new Dictionary<Mobile, Timer>();
m_Teleporting = new Dictionary<Mobile, TimerExecutionToken>();
var count = reader.ReadInt();

View file

@ -129,7 +129,7 @@ namespace Server.Items
}
}
Timer.DelayCall(StopBroadcasting);
Timer.StartTimer(StopBroadcasting);
}
private void StopBroadcasting()