modernuo/Projects/Server/Timer/Timer.cs

241 lines
6.5 KiB
C#
Raw Permalink Normal View History

/*************************************************************************
* ModernUO *
* Copyright 2019-2024 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Timer.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/>. *
*************************************************************************/
2020-08-25 18:53:35 -07:00
using System;
using System.Diagnostics;
using Server.Logging;
2020-08-25 18:53:35 -07:00
namespace Server;
public partial class Timer
2020-08-25 18:53:35 -07:00
{
protected internal static readonly ILogger logger = LogFactory.GetLogger(typeof(Timer));
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);`.
2021-08-07 14:33:35 -07:00
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;
private TimeSpan _delay;
private TimeSpan _interval;
2020-08-25 18:53:35 -07:00
public Timer(TimeSpan delay) => Init(delay, TimeSpan.Zero, 1);
feat: Adds auto archiving (#794) ## Adds Auto Archiving Backups are archived once an hour, day, and month. Archives older than 60 days are pruned automatically. _Note: Automatic pruning is off by default_ ### Archive compression format The following formats are supported: * Zstd (The fastest with best compression ratio) * GZip * Zip * None (Tar) _Note: By default archives use [zstandard](http://facebook.github.io/zstd/) format. The archive format can be changed in modernuo.json `autoArchive.compressionFormat`_ ### Restoring world from archive Move the archive to the Saves folder (tar.zst file). On startup the server will extract the file and restore the latest save. See pictures below. ### Manually extracting an archives #### Windows * Use the latest version of [7-zip w/ ZStandard](https://github.com/mcmilk/7-Zip-zstd/releases/latest) 1. Extract the `.tar.zst` file. 2. Extract the `.tar` file. (Yes you have to do it in two steps) * On Windows 10 you can use the command line. `zstd.exe` is in the Assemblies folder after building ModernUO. 1. `tar --use-compress-program "Distribution\Assemblies\zstd.exe -d" -xvf "Archives\Hourly\archivefile.tar.zst" -C "path to where you want to extract it"` #### Mac * Install [Keka](https://www.keka.io) 1. Drop the .tar.zst onto the keka interface. #### Linux 1. Install zstd from a package manager 2. Run `tar -I zstd -xvf "Archives\Hourly\archivefile.tar.zst" -C "path to where you want to extract it"` ### Other changes * Changes Autosave to occur at the same time no matter when the server is booted. * Adds `[SaveFrequency <delay> [warning]`command to set save frequency and warning frequency in-game. * Adds support for time zones that are configurable. The system timezone can also be manually configured. Check `TimeZoneHandler.cs` for details. <img width="257" alt="Screen Shot 2021-09-22 at 11 23 18 PM" src="https://user-images.githubusercontent.com/3953314/134464929-a5bf3cd8-2ef0-4476-a9ad-71d0816a19ac.png"> <img width="241" alt="Screen Shot 2021-09-22 at 11 23 39 PM" src="https://user-images.githubusercontent.com/3953314/134464945-5f6f96dc-3d1e-434d-8256-5c6b3705e786.png"> <img width="836" alt="Screen Shot 2021-09-22 at 11 34 39 PM" src="https://user-images.githubusercontent.com/3953314/134464957-625e57f2-ef47-4ca1-a0a7-cd40c9b6539c.png"> <img width="631" alt="Screen Shot 2021-09-22 at 11 34 50 PM" src="https://user-images.githubusercontent.com/3953314/134464969-b2d65c0d-f8f5-497a-a832-5d805e8e0b22.png">
2021-09-25 17:22:05 -07:00
public Timer(TimeSpan interval, int count) => Init(interval, interval, count);
2020-08-25 18:53:35 -07:00
public Timer(TimeSpan delay, TimeSpan interval, int count = 0) => Init(delay, interval, count);
protected void Init(TimeSpan delay, TimeSpan interval, int count)
{
Delay = delay;
Next = DateTime.MinValue;
Interval = interval;
Count = count;
Running = false;
Index = 0;
_nextTimer = null;
_prevTimer = null;
_ring = -1;
_slot = -1;
}
2020-08-25 18:53:35 -07:00
protected int Version { get; set; } // Used to determine if a timer was altered and we should abandon it.
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);`.
2021-08-07 14:33:35 -07:00
public DateTime Next { get; private set; }
public TimeSpan Delay
{
get => _delay;
set => _delay = TimeSpan.FromMilliseconds(RoundTicksToNextPowerOfTwo((long)value.TotalMilliseconds));
}
public TimeSpan Interval
{
get => _interval;
set => _interval = TimeSpan.FromMilliseconds(RoundTicksToNextPowerOfTwo((long)value.TotalMilliseconds));
}
public int Index { get; private set; }
public int Count { get; private set; }
public int RemainingCount => Count == 0 ? int.MaxValue : Count - Index;
public bool Running { get; private set; }
public override string ToString() => GetType().FullName;
2020-08-25 18:53:35 -07:00
public Timer Start()
{
if (World.WorldState is WorldState.Saving)
{
logger.Error(
$"Attempted to start timer {{Timer}} ({{HashCode}}) while world is {{State}}{Environment.NewLine}{{StackTrace}}",
GetType(),
GetHashCode(),
World.WorldState,
new StackTrace()
);
}
#if THREADGUARD
if (Thread.CurrentThread != Core.Thread)
{
logger.Error(
$"Attempted to start timer {{Timer}} ({{HashCode}}) from an invalid thread!{Environment.NewLine}{{StackTrace}}",
GetType(),
GetHashCode(),
new StackTrace()
);
}
#endif
if (Running)
2020-08-25 18:53:35 -07:00
{
return this;
}
2020-08-25 18:53:35 -07:00
Index = 0;
Running = true;
AddTimer(this, (long)Delay.TotalMilliseconds);
return this;
}
public void Stop()
{
if (World.WorldState is WorldState.Saving)
{
logger.Error(
$"Attempted to stop timer {{Timer}} ({{HashCode}}) while world is {{State}}{Environment.NewLine}{{StackTrace}}",
GetType(),
GetHashCode(),
World.WorldState,
new StackTrace()
);
}
#if THREADGUARD
if (Thread.CurrentThread != Core.Thread)
{
logger.Error(
$"Attempted to stop timer {{Timer}} ({{HashCode}}) from an invalid thread!{Environment.NewLine}{{StackTrace}}",
GetType(),
GetHashCode(),
new StackTrace()
);
}
#endif
if (!Running)
{
return;
}
InternalStop();
Detach();
OnDetach();
Version++;
}
private void InternalStop()
{
Running = false;
2020-08-25 18:53:35 -07:00
// We are the head on the timer ring
if (_rings[_ring][_slot] == this)
{
_rings[_ring][_slot] = _nextTimer;
}
// We are the head on the executing ring
if (_executingRings[_ring] == this)
{
_executingRings[_ring] = _nextTimer;
}
}
protected virtual void OnTick()
{
}
private void Attach(Timer timer)
{
#if DEBUG_TIMERS
if (_nextTimer != null)
{
logger.Error(
"{Timer} ({HashCode}) attached with a next timer already set!",
this,
GetHashCode()
);
}
#endif
_nextTimer = timer;
if (timer != null)
{
#if DEBUG_TIMERS
if (timer._prevTimer != null)
{
logger.Error(
"{Timer} ({HashCode}) attached from with a previous timer already set!",
timer,
timer.GetHashCode()
);
}
#endif
timer._prevTimer = this;
}
}
private void Detach()
{
if (_prevTimer != null)
{
_prevTimer._nextTimer = _nextTimer;
}
if (_nextTimer != null)
{
_nextTimer._prevTimer = _prevTimer;
}
_nextTimer = null;
_prevTimer = null;
}
internal virtual void OnDetach()
{
if (Running)
{
logger.Error(
$"{{Timer}} detached while still running!{Environment.NewLine}{{StackTrace}}",
this,
new StackTrace()
);
return;
}
_ring = -1;
_slot = -1;
2020-08-25 18:53:35 -07:00
}
}