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

@ -14,252 +14,222 @@
*************************************************************************/
using System;
#if DEBUG_TIMERS
using System.Collections.Generic;
#endif
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Server
{
public delegate void TimerStateCallback<in T>(T state);
public delegate void TimerStateCallback<in T1, in T2>(T1 t1, T2 t2);
public delegate void TimerStateCallback<in T1, in T2, in T3>(T1 t1, T2 t2, T3 t3);
public delegate void TimerStateCallback<in T1, in T2, in T3, in T4>(T1 t1, T2 t2, T3 t3, T4 t4);
public partial class Timer
{
private static string FormatDelegate(Delegate callback) =>
callback == null ? "null" : $"{callback.Method.DeclaringType?.FullName ?? ""}.{callback.Method.Name}";
public static Timer DelayCall(Action callback) => DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(Action callback) => DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback);
public static Timer DelayCall(TimeSpan delay, Action callback) =>
DelayCall(delay, TimeSpan.Zero, 1, callback);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(TimeSpan delay, Action callback) => DelayCall(delay, TimeSpan.Zero, 1, callback);
public static Timer DelayCall(TimeSpan delay, TimeSpan interval, Action callback) =>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, Action callback) =>
DelayCall(delay, interval, 0, callback);
public static Timer DelayCall(TimeSpan delay, TimeSpan interval, int count, Action callback)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(TimeSpan interval, int count, Action callback) =>
DelayCall(TimeSpan.Zero, interval, count, callback);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, int count, Action callback)
{
Timer t = new DelayCallTimer(delay, interval, count, callback);
DelayCallTimer t = new DelayCallTimer(delay, interval, count, callback);
t.Start();
#if DEBUG_TIMERS
t._allowFinalization = true;
#endif
return t;
}
public static Timer DelayCall<T>(TimerStateCallback<T> callback, T state) =>
DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, state);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(Action callback) => StartTimer(TimeSpan.Zero, TimeSpan.Zero, 1, callback);
public static Timer DelayCall<T>(TimeSpan delay, TimerStateCallback<T> callback, T state) =>
DelayCall(delay, TimeSpan.Zero, 1, callback, state);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, Action callback) => StartTimer(delay, TimeSpan.Zero, 1, callback);
public static Timer DelayCall<T>(TimeSpan delay, TimeSpan interval, TimerStateCallback<T> callback, T state) =>
DelayCall(delay, interval, 0, callback, state);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback) =>
StartTimer(delay, interval, 0, callback);
public static Timer DelayCall<T>(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T> callback,
T state
)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan interval, int count, Action callback) =>
StartTimer(TimeSpan.Zero, interval, count, callback);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback)
{
Timer t = new DelayStateCallTimer<T>(delay, interval, count, callback, state);
DelayCallTimer t = DelayCallTimer.GetTimer(delay, interval, count, callback);
t._selfReturn = true;
t.Start();
return t;
#if DEBUG_TIMERS
DelayCallTimer._stackTraces[t.GetHashCode()] = new StackTrace().ToString();
#endif
}
public static Timer DelayCall<T1, T2>(TimerStateCallback<T1, T2> callback, T1 t1, T2 t2) =>
DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, t1, t2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(Action callback, out TimerExecutionToken token) =>
StartTimer(TimeSpan.Zero, TimeSpan.Zero, 1, callback, out token);
public static Timer DelayCall<T1, T2>(TimeSpan delay, TimerStateCallback<T1, T2> callback, T1 t1, T2 t2) =>
DelayCall(delay, TimeSpan.Zero, 1, callback, t1, t2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, Action callback, out TimerExecutionToken token) =>
StartTimer(delay, TimeSpan.Zero, 1, callback, out token);
public static Timer DelayCall<T1, T2>(
TimeSpan delay, TimeSpan interval, TimerStateCallback<T1, T2> callback,
T1 t1, T2 t2
) => DelayCall(delay, interval, 0, callback, t1, t2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback, out TimerExecutionToken token) =>
StartTimer(delay, interval, 0, callback, out token);
public static Timer DelayCall<T1, T2>(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T1, T2> callback,
T1 t1, T2 t2
)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan interval, int count, Action callback, out TimerExecutionToken token) =>
StartTimer(TimeSpan.Zero, interval, count, callback, out token);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback, out TimerExecutionToken token)
{
Timer t = new DelayStateCallTimer<T1, T2>(delay, interval, count, callback, t1, t2);
DelayCallTimer t = DelayCallTimer.GetTimer(delay, interval, count, callback);
t.Start();
return t;
#if DEBUG_TIMERS
DelayCallTimer._stackTraces[t.GetHashCode()] = new StackTrace().ToString();
#endif
token = new TimerExecutionToken(t);
}
public static Timer DelayCall<T1, T2, T3>(TimerStateCallback<T1, T2, T3> callback, T1 t1, T2 t2, T3 t3) =>
DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, t1, t2, t3);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer Pause(TimeSpan ms) => new(ms);
public static Timer DelayCall<T1, T2, T3>(
TimeSpan delay, TimerStateCallback<T1, T2, T3> callback, T1 t1, T2 t2, T3 t3
) =>
DelayCall(delay, TimeSpan.Zero, 1, callback, t1, t2, t3);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer Pause(int ms) => Pause(TimeSpan.FromMilliseconds(ms));
public static Timer DelayCall<T1, T2, T3>(
TimeSpan delay, TimeSpan interval, TimerStateCallback<T1, T2, T3> callback,
T1 t1, T2 t2, T3 t3
) => DelayCall(delay, interval, 0, callback, t1, t2, t3);
public static Timer DelayCall<T1, T2, T3>(
TimeSpan delay, TimeSpan interval, int count,
TimerStateCallback<T1, T2, T3> callback, T1 t1, T2 t2, T3 t3
)
public sealed class DelayCallTimer : Timer, INotifyCompletion
{
Timer t = new DelayStateCallTimer<T1, T2, T3>(delay, interval, count, callback, t1, t2, t3);
t.Start();
internal bool _selfReturn;
#if DEBUG_TIMERS
internal bool _allowFinalization;
#endif
private Action _continuation;
private bool _complete;
return t;
}
public static Timer DelayCall<T1, T2, T3, T4>(
TimerStateCallback<T1, T2, T3, T4> callback, T1 t1, T2 t2, T3 t3, T4 t4
) =>
DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, t1, t2, t3, t4);
public static Timer DelayCall<T1, T2, T3, T4>(
TimeSpan delay, TimerStateCallback<T1, T2, T3, T4> callback,
T1 t1, T2 t2, T3 t3, T4 t4
) => DelayCall(delay, TimeSpan.Zero, 1, callback, t1, t2, t3, t4);
public static Timer DelayCall<T1, T2, T3, T4>(
TimeSpan delay, TimeSpan interval,
TimerStateCallback<T1, T2, T3, T4> callback, T1 t1, T2 t2, T3 t3, T4 t4
) =>
DelayCall(delay, interval, 0, callback, t1, t2, t3, t4);
public static Timer DelayCall<T1, T2, T3, T4>(
TimeSpan delay, TimeSpan interval, int count,
TimerStateCallback<T1, T2, T3, T4> callback, T1 t1, T2 t2, T3 t3, T4 t4
)
{
Timer t = new DelayStateCallTimer<T1, T2, T3, T4>(delay, interval, count, callback, t1, t2, t3, t4);
t.Start();
return t;
}
private class DelayCallTimer : Timer
{
public DelayCallTimer(TimeSpan delay, TimeSpan interval, int count, Action callback) : base(
internal DelayCallTimer(TimeSpan delay, TimeSpan interval, int count, Action callback) : base(
delay,
interval,
count
)
{
Callback = callback;
}
) =>
_continuation = callback;
public Action Callback { get; }
internal DelayCallTimer(TimeSpan delay) : base(delay)
{
#if DEBUG_TIMERS
t._allowFinalization = true;
#endif
Start();
}
protected override void OnTick()
{
Callback?.Invoke();
_complete = true;
_continuation?.Invoke();
}
public override string ToString() => $"DelayCallTimer[{FormatDelegate(Callback)}]";
}
private class DelayStateCallTimer<T> : Timer
{
private readonly T m_State;
public DelayStateCallTimer(TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T> callback, T state)
: base(delay, interval, count)
public override void Stop()
{
Callback = callback;
m_State = state;
base.Stop();
if (_selfReturn)
{
Return();
}
}
public TimerStateCallback<T> Callback { get; }
protected override void OnTick()
internal void Return()
{
Callback?.Invoke(m_State);
if (Running)
{
logger.Error($"Timer is returned while still running! {new StackTrace()}");
return;
}
Version++; // Increment the version so if this is called from OnTick() and another timer is started, we don't have a problem
if (_poolCount >= _poolCapacity)
{
#if DEBUG_TIMERS
logger.Warning($"DelayCallTimer pool reached maximum of {_poolSize} timers");
_allowFinalization = true;
_stackTraces.Remove(GetHashCode());
#endif
return;
}
_continuation = null;
ReturnToPool(1, this, this);
}
public override string ToString() => $"DelayStateCall[{FormatDelegate(Callback)}]";
}
private class DelayStateCallTimer<T1, T2> : Timer
{
private readonly T1 m_T1;
private readonly T2 m_T2;
public DelayStateCallTimer(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T1, T2> callback,
T1 t1, T2 t2
) : base(delay, interval, count)
public static DelayCallTimer GetTimer(TimeSpan delay, TimeSpan interval, int count, Action callback)
{
Callback = callback;
m_T1 = t1;
m_T2 = t2;
if (_poolHead != null)
{
_poolCount--;
#if DEBUG_TIMERS
logger.Information($"Pool count changed: {_poolCount} ({_poolCapacity})");
#endif
var timer = GetFromPool();
timer.Init(delay, interval, count);
timer._continuation = callback;
timer._selfReturn = false;
#if DEBUG_TIMERS
timer._allowFinalization = false;
#endif
return timer;
}
_timerPoolDepletionAmount++;
#if DEBUG_TIMERS
logger.Warning($"Timer pool depleted and timer was allocated.\n{new StackTrace()});
#endif
return new DelayCallTimer(delay, interval, count, callback);
}
public TimerStateCallback<T1, T2> Callback { get; }
public override string ToString() => $"DelayCallTimer[{FormatDelegate(_continuation)}]";
protected override void OnTick()
#if DEBUG_TIMERS
internal static Dictionary<int, string> _stackTraces = new();
~DelayCallTimer()
{
Callback?.Invoke(m_T1, m_T2);
if (!_allowFinalization)
{
logger.Warning($"Pooled timer was not returned to the pool.\n{_stackTraces[GetHashCode()]}");
}
}
#endif
public override string ToString() => $"DelayStateCall[{FormatDelegate(Callback)}]";
}
public DelayCallTimer GetAwaiter() => this;
private class DelayStateCallTimer<T1, T2, T3> : Timer
{
private readonly T1 m_T1;
private readonly T2 m_T2;
private readonly T3 m_T3;
public bool IsCompleted => _complete;
public DelayStateCallTimer(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T1, T2, T3> callback,
T1 t1, T2 t2, T3 t3
) : base(delay, interval, count)
public void OnCompleted(Action continuation) => _continuation = continuation;
public void GetResult()
{
Callback = callback;
m_T1 = t1;
m_T2 = t2;
m_T3 = t3;
}
public TimerStateCallback<T1, T2, T3> Callback { get; }
protected override void OnTick()
{
Callback?.Invoke(m_T1, m_T2, m_T3);
}
public override string ToString() => $"DelayStateCall[{FormatDelegate(Callback)}]";
}
private class DelayStateCallTimer<T1, T2, T3, T4> : Timer
{
private readonly T1 m_T1;
private readonly T2 m_T2;
private readonly T3 m_T3;
private readonly T4 m_T4;
public DelayStateCallTimer(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T1, T2, T3, T4> callback,
T1 t1, T2 t2, T3 t3, T4 t4
) : base(delay, interval, count)
{
Callback = callback;
m_T1 = t1;
m_T2 = t2;
m_T3 = t3;
m_T4 = t4;
}
public TimerStateCallback<T1, T2, T3, T4> Callback { get; }
protected override void OnTick()
{
Callback?.Invoke(m_T1, m_T2, m_T3, m_T4);
}
public override string ToString() => $"DelayStateCall[{FormatDelegate(Callback)}]";
}
}
}

View file

@ -1,53 +0,0 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Timer.Pause.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Runtime.CompilerServices;
namespace Server
{
public partial class Timer
{
public class DelayTaskTimer : Timer, INotifyCompletion
{
private Action _continuation;
private bool _complete;
internal DelayTaskTimer(TimeSpan delay) : base(delay) => Start();
protected override void OnTick()
{
_complete = true;
_continuation?.Invoke();
}
public DelayTaskTimer GetAwaiter() => this;
public bool IsCompleted => _complete;
public void OnCompleted(Action continuation) => _continuation = continuation;
public void GetResult()
{
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayTaskTimer Pause(TimeSpan ms) => new(ms);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayTaskTimer Pause(int ms) => Pause(TimeSpan.FromMilliseconds(ms));
}
}

View file

@ -0,0 +1,128 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Timer.Pool.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Threading;
namespace Server
{
public partial class Timer
{
private const int _timerPoolDepletionThreshold = 128; // Maximum timers allocated in a single tick before we force adjust
private static int _timerPoolDepletionAmount; // Amount the pool has been depleted by
private static int _maxPoolCapacity;
private static int _poolCapacity;
private static int _poolCount;
private static DelayCallTimer _poolHead;
public static void CheckTimerPool()
{
// Anything less than this threshold and we are ok with the number of allocations.
if (_timerPoolDepletionAmount < _timerPoolDepletionThreshold)
{
_timerPoolDepletionAmount = 0;
return;
}
var growthFactor = Math.DivRem(_timerPoolDepletionAmount, _poolCapacity, out var rem);
var amountToGrow = _poolCapacity * (growthFactor + (rem > 0 ? 1 : 0));
var amountToRefill = Math.Min(_maxPoolCapacity, amountToGrow);
var maximumHit = amountToGrow > amountToRefill ? " Maximum pool size has been reached." : "";
logger.Warning($"Timer pool depleted by {_timerPoolDepletionAmount}. Refilling with {amountToRefill}.{maximumHit}");
RefillPoolAsync(amountToRefill);
_timerPoolDepletionAmount = 0;
}
public static void ConfigureTimerPool()
{
_poolCapacity = ServerConfiguration.GetOrUpdateSetting("timer.intialPoolCapacity", 1024);
_maxPoolCapacity = ServerConfiguration.GetOrUpdateSetting("timer.maxPoolCapacity", _poolCapacity * 16);
RefillPool(_poolCapacity, out var head, out var tail);
ReturnToPool(_poolCapacity, head, tail);
}
private static void ReturnToPool(int amount, DelayCallTimer head, DelayCallTimer tail)
{
tail.Attach(_poolHead);
_poolHead = head;
_poolCount += amount;
#if DEBUG_TIMERS
logger.Information($"Pool count changed: {_poolCount} ({_poolCapacity})");
#endif
}
private static DelayCallTimer GetFromPool()
{
var timer = _poolHead;
_poolHead = _poolHead._nextTimer as DelayCallTimer;
timer.Detach();
return timer;
}
internal static void RefillPool(int amount, out DelayCallTimer head, out DelayCallTimer tail)
{
#if DEBUG_TIMERS
logger.Information($"Filling pool with {amount} timers.");
#endif
head = null;
tail = null;
for (var i = 0; i < amount; i++)
{
var timer = new DelayCallTimer(TimeSpan.Zero, TimeSpan.Zero, 0, null);
timer.Attach(head);
if (i == 0)
{
tail = timer;
}
head = timer;
}
}
internal static void RefillPoolAsync(int amountToRefill)
{
ThreadPool.UnsafeQueueUserWorkItem(
static amount =>
{
RefillPool(amount, out var head, out var tail);
// Run this on the core thread
Core.LoopContext.Post(
state =>
{
if (state == null)
{
return;
}
var (listHead, listTail) = ((DelayCallTimer, DelayCallTimer))state;
ReturnToPool(amount, listHead, listTail);
_poolCapacity = amount;
},
(head, tail)
);
},
amountToRefill,
false
);
}
}
}

View file

@ -113,20 +113,25 @@ namespace Server
// This can be done in OnTick by checking if Index < Count - 1 (still more iterations left)
RemoveTimer(timer);
if (finished)
{
timer.InternalStop();
}
var version = timer.Version;
prof?.Start();
timer.OnTick();
prof?.Finish();
if (timer.Running && !finished)
// If the timer has not been stopped, and it has not been altered (shared timers)
if (timer.Running && timer.Version == version)
{
timer.Delay = timer.Interval;
timer.Next = Core.Now + timer.Interval;
AddTimer(timer, (long)timer.Delay.TotalMilliseconds);
if (finished)
{
timer.Stop();
}
else
{
timer.Delay = timer.Interval;
timer.Next = Core.Now + timer.Interval;
AddTimer(timer, (long)timer.Delay.TotalMilliseconds);
}
}
timer = next;
@ -200,8 +205,8 @@ namespace Server
{
var now = DateTime.UtcNow;
tw.WriteLine("Date: {0}", now);
tw.WriteLine();
tw.WriteLine("Date: {0}\n", now);
tw.WriteLine("Pool - Count: {0}; Size {1}\n", _poolCount - _timerPoolDepletionAmount, _poolCapacity);
var total = 0.0;
var hash = new Dictionary<string, int>();
@ -221,9 +226,11 @@ namespace Server
}
}
tw.WriteLine("Timers:");
foreach (var (name, count) in hash.OrderByDescending(o => o.Value))
{
tw.WriteLine($"Type: {name}; Count: {count}; Percent: {count / total}%");
tw.WriteLine($"- Type: {name}; Count: {count}; Percent: {count / total}%");
}
tw.WriteLine();

View file

@ -21,12 +21,16 @@ namespace Server
{
public partial class Timer
{
private static readonly ILogger logger = LogFactory.GetLogger(typeof(Timer));
protected internal static readonly ILogger logger = LogFactory.GetLogger(typeof(Timer));
public static void Configure()
{
ConfigureTimerPool();
}
// We need to know what ring/slot we are in so we can be removed if we are "head" of the link list.
private int _ring;
private int _slot;
private long _remaining;
private Timer _nextTimer;
private Timer _prevTimer;
@ -37,10 +41,11 @@ namespace Server
public Timer(TimeSpan delay, TimeSpan interval, int count = 0) => Init(delay, interval, count);
public void Init(TimeSpan delay, TimeSpan interval, int count)
protected void Init(TimeSpan delay, TimeSpan interval, int count)
{
Running = false;
Delay = delay;
Index = 0;
Interval = interval;
Count = count;
_nextTimer = null;
@ -55,6 +60,8 @@ namespace Server
}
}
protected int Version { get; set; } // Used to determine if a timer was altered and we should abandon it.
public DateTime Next { get; private set; }
public TimeSpan Delay { get; set; }
public TimeSpan Interval { get; set; }
@ -87,21 +94,14 @@ namespace Server
return this;
}
public Timer Stop()
public virtual void Stop()
{
if (!Running)
{
return this;
return;
}
RemoveTimer(this);
InternalStop();
return this;
}
private void InternalStop()
{
Running = false;
var prof = GetProfile();

View file

@ -0,0 +1,60 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: TimerExecutionToken.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Runtime.CompilerServices;
namespace Server
{
public struct TimerExecutionToken
{
private Timer.DelayCallTimer _timer;
internal TimerExecutionToken(Timer.DelayCallTimer timer) => _timer = timer;
public bool Running
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _timer?.Running == true;
}
public int Index
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _timer?.Index ?? 0;
}
public int RemainingCount
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _timer?.RemainingCount ?? 0;
}
public DateTime Next
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _timer?.Next ?? DateTime.MinValue;
}
public void Cancel()
{
_timer?.Stop();
_timer?.Return();
_timer = null;
this = default;
}
}
}