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

@ -8,7 +8,7 @@ namespace Server.Engines.Quests
{
private int m_Charges;
private Timer m_PlayTimer;
private TimerExecutionToken _timerToken;
[Constructible]
public HornOfRetreat() : base(0xFC4)
@ -62,7 +62,7 @@ namespace Server.Engines.Quests
{
from.SendLocalizedMessage(1076154); // You can only use this in Trammel and Malas.
}
else if (m_PlayTimer != null)
else if (_timerToken.Running)
{
SendLocalizedMessageTo(from, 1042144); // This is currently in use.
}
@ -74,7 +74,7 @@ namespace Server.Engines.Quests
--Charges;
m_PlayTimer = Timer.DelayCall(TimeSpan.FromSeconds(5.0), PlayTimer_Callback, from);
Timer.StartTimer(TimeSpan.FromSeconds(5.0), () => PlayTimer_Callback(from), out _timerToken);
}
else
{
@ -89,7 +89,7 @@ namespace Server.Engines.Quests
public virtual void PlayTimer_Callback(Mobile from)
{
m_PlayTimer = null;
_timerToken.Cancel();
var gate = new HornOfRetreatMoongate(DestLoc, DestMap, from, Hue);
@ -146,7 +146,7 @@ namespace Server.Engines.Quests
Dispellable = false;
Timer.DelayCall(TimeSpan.FromSeconds(10.0), Delete);
Timer.StartTimer(TimeSpan.FromSeconds(10.0), Delete);
}
public HornOfRetreatMoongate(Serial serial) : base(serial)

View file

@ -38,7 +38,7 @@ namespace Server.Engines.Quests
typeof(TerribleHatchlingsQuest)
};
private Timer m_Timer;
private TimerExecutionToken _timerToken;
public QuestSystem(PlayerMobile from)
{
@ -69,19 +69,18 @@ namespace Server.Engines.Quests
public virtual void StartTimer()
{
if (m_Timer != null)
if (_timerToken.Running)
{
return;
}
m_Timer = Timer.DelayCall(TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(0.5), Slice);
// TODO: Find out if this can go on forever. We should not allow timers to leak if this is the case.
Timer.StartTimer(TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(0.5), Slice, out _timerToken);
}
public virtual void StopTimer()
{
m_Timer?.Stop();
m_Timer = null;
_timerToken.Cancel();
}
public virtual void Slice()
@ -344,36 +343,38 @@ namespace Server.Engines.Quests
{
StopTimer();
if (From.Quest == this)
if (From.Quest != this)
{
From.Quest = null;
return;
}
var restartDelay = RestartDelay;
From.Quest = null;
if (completed && restartDelay > TimeSpan.Zero || !completed && restartDelay == TimeSpan.MaxValue)
var restartDelay = RestartDelay;
if (completed && restartDelay > TimeSpan.Zero || !completed && restartDelay == TimeSpan.MaxValue)
{
From.DoneQuests ??= new List<QuestRestartInfo>();
var found = false;
var ourQuestType = GetType();
for (var i = 0; i < From.DoneQuests.Count; ++i)
{
From.DoneQuests ??= new List<QuestRestartInfo>();
var restartInfo = From.DoneQuests[i];
var found = false;
var ourQuestType = GetType();
for (var i = 0; i < From.DoneQuests.Count; ++i)
if (restartInfo.QuestType == ourQuestType)
{
var restartInfo = From.DoneQuests[i];
if (restartInfo.QuestType == ourQuestType)
{
restartInfo.Reset(restartDelay);
found = true;
break;
}
restartInfo.Reset(restartDelay);
found = true;
break;
}
}
if (!found)
{
From.DoneQuests.Add(new QuestRestartInfo(ourQuestType, restartDelay));
}
if (!found)
{
From.DoneQuests.Add(new QuestRestartInfo(ourQuestType, restartDelay));
}
}
}

View file

@ -44,7 +44,7 @@ namespace Server.Engines.Quests.Necro
Maabus = new Maabus { Location = SpawnLocation, Map = Map };
Maabus.Direction = Maabus.GetDirectionTo(caller);
Timer.DelayCall(TimeSpan.FromSeconds(7.5), BeginSleep);
Timer.StartTimer(TimeSpan.FromSeconds(7.5), BeginSleep);
}
public void BeginSleep()
@ -56,7 +56,7 @@ namespace Server.Engines.Quests.Necro
Effects.PlaySound(Maabus.Location, Maabus.Map, 0x48E);
Timer.DelayCall(TimeSpan.FromSeconds(2.5), Sleep);
Timer.StartTimer(TimeSpan.FromSeconds(2.5), Sleep);
}
public void Sleep()

View file

@ -91,7 +91,7 @@ namespace Server.Engines.Quests.Necro
m_ToDelete = true;
Timer.DelayCall(TimeSpan.FromSeconds(5.0), Delete);
Timer.StartTimer(TimeSpan.FromSeconds(5.0), Delete);
}
else if (m_Necromancer.Map != Map || GetDistanceToSqrt(m_Necromancer) > RangePerception + 1)
{
@ -239,7 +239,7 @@ namespace Server.Engines.Quests.Necro
Hue = 0x482;
Light = LightType.Circle300;
Timer.DelayCall(TimeSpan.FromSeconds(10.0), Delete);
Timer.StartTimer(TimeSpan.FromSeconds(10.0), Delete);
}
public SummonedPaladinMoongate(Serial serial) : base(serial)

View file

@ -82,7 +82,7 @@ namespace Server.Engines.Quests.Samurai
}
}
Timer.DelayCall(TimeSpan.FromMinutes(2.0), GenerateTreasure);
Timer.StartTimer(TimeSpan.FromMinutes(2.0), GenerateTreasure);
}
public override void Serialize(IGenericWriter writer)
@ -98,7 +98,7 @@ namespace Server.Engines.Quests.Samurai
var version = reader.ReadEncodedInt();
Timer.DelayCall(GenerateTreasure);
Timer.StartTimer(GenerateTreasure);
}
}
}

View file

@ -39,16 +39,14 @@ namespace Server.Engines.Quests.Naturalist
if (m_CurrentNest.Special)
{
from.SendLocalizedMessage(
1054057
); // You complete your examination of this bizarre Egg Nest. The Naturalist will undoubtedly be quite interested in these notes!
// You complete your examination of this bizarre Egg Nest. The Naturalist will undoubtedly be quite interested in these notes!
from.SendLocalizedMessage(1054057);
StudiedSpecialNest = true;
}
else
{
from.SendLocalizedMessage(
1054054
); // You have completed your study of this Solen Egg Nest. You put your notes away.
// You have completed your study of this Solen Egg Nest. You put your notes away.
from.SendLocalizedMessage(1054054);
CurProgress++;
}
}
@ -56,9 +54,8 @@ namespace Server.Engines.Quests.Naturalist
{
if (!nest.Special)
{
from.SendLocalizedMessage(
1054058
); // You begin recording your completed notes on a bit of parchment.
// You begin recording your completed notes on a bit of parchment.
from.SendLocalizedMessage(1054058);
}
m_StudyState = StudyState.SecondStep;
@ -69,9 +66,8 @@ namespace Server.Engines.Quests.Naturalist
{
if (m_StudyState != StudyState.Inactive)
{
from.SendLocalizedMessage(
1054046
); // You abandon your study of the Solen Egg Nest without gathering the needed information.
// You abandon your study of the Solen Egg Nest without gathering the needed information.
from.SendLocalizedMessage(1054046);
}
m_CurrentNest = null;
@ -90,9 +86,8 @@ namespace Server.Engines.Quests.Naturalist
{
m_StudyState = StudyState.Inactive;
from.SendLocalizedMessage(
1054047
); // You glance at the Egg Nest, realizing you've already studied this one.
// You glance at the Egg Nest, realizing you've already studied this one.
from.SendLocalizedMessage(1054047);
}
else
{
@ -100,15 +95,13 @@ namespace Server.Engines.Quests.Naturalist
if (nest.Special)
{
from.SendLocalizedMessage(
1054056
); // You notice something very odd about this Solen Egg Nest. You begin taking notes.
// You notice something very odd about this Solen Egg Nest. You begin taking notes.
from.SendLocalizedMessage(105405);
}
else
{
from.SendLocalizedMessage(
1054045
); // You begin studying the Solen Egg Nest to gather information.
// You begin studying the Solen Egg Nest to gather information.
from.SendLocalizedMessage(1054045);
}
if (from.Female)

View file

@ -61,7 +61,7 @@ namespace Server.Engines.Quests.Doom
Effects.PlaySound(GetWorldLocation(), Map, 0x100);
Timer.DelayCall(TimeSpan.FromSeconds(8.0), EndSummon, from);
Timer.StartTimer(TimeSpan.FromSeconds(8.0), () => EndSummon(from));
}
}

View file

@ -56,7 +56,7 @@ namespace Server.Engines.Quests.Doom
return;
}
Timer.DelayCall(TimeSpan.FromSeconds(4.0), EndGiveWarning);
Timer.StartTimer(TimeSpan.FromSeconds(4.0), EndGiveWarning);
}
public virtual void EndGiveWarning()
@ -84,12 +84,12 @@ namespace Server.Engines.Quests.Doom
return;
}
Timer.DelayCall(TimeSpan.FromSeconds(30.0), EndSummonDragon);
Timer.StartTimer(TimeSpan.FromSeconds(30.0), EndSummonDragon);
}
public virtual void BeginRemove(TimeSpan delay)
{
Timer.DelayCall(delay, EndRemove);
Timer.StartTimer(delay, EndRemove);
}
public virtual void EndRemove()

View file

@ -94,7 +94,7 @@ namespace Server.Engines.Quests.Hag
{
PublicOverheadMessage(MessageType.Regular, 0x3B2, 500849); // *hic*
Timer.DelayCall(TimeSpan.FromSeconds(Utility.RandomMinMax(60, 180)), Heave);
Timer.StartTimer(TimeSpan.FromSeconds(Utility.RandomMinMax(60, 180)), Heave);
}
public override void Serialize(IGenericWriter writer)

View file

@ -58,7 +58,7 @@ namespace Server.Engines.Quests.Hag
// * You see a strange imp stealing a scrap of paper from the bloodied corpse *
Corpse.SendLocalizedMessageTo(player, 1055049);
Timer.DelayCall(TimeSpan.FromSeconds(3.0), DeleteImp, imp);
Timer.StartTimer(TimeSpan.FromSeconds(3.0), () => DeleteImp(imp));
}
private void DeleteImp(Mobile m)
@ -221,7 +221,7 @@ namespace Server.Engines.Quests.Hag
imp.Direction = imp.GetDirectionTo(from);
Timer.DelayCall(TimeSpan.FromSeconds(3.0), DeleteImp, imp);
Timer.StartTimer(TimeSpan.FromSeconds(3.0), () => DeleteImp(imp));
}
private void DeleteImp(object imp)