using System; using System.Timers; using Artemis.Core.Modules; namespace Artemis.Core { /// /// Represents a registration for a timed plugin update /// public class PluginUpdateRegistration { private DateTime _lastEvent; private Timer _timer; internal PluginUpdateRegistration(PluginInfo pluginInfo, TimeSpan interval, Action action) { PluginInfo = pluginInfo; Interval = interval; Action = action; PluginInfo.Instance.PluginEnabled += InstanceOnPluginEnabled; PluginInfo.Instance.PluginDisabled += InstanceOnPluginDisabled; if (PluginInfo.Instance.Enabled) Start(); } /// /// Gets the plugin info of the plugin this registration is associated with /// public PluginInfo PluginInfo { get; } /// /// Gets the interval at which the update should occur /// public TimeSpan Interval { get; } /// /// Gets the action that gets called each time the update event fires /// public Action Action { get; } /// /// Starts calling the at the configured /// Note: Called automatically when the plugin enables /// public void Start() { lock (this) { if (!PluginInfo.Instance.Enabled) throw new ArtemisPluginException("Cannot start a timed update for a disabled plugin"); if (_timer != null) return; // Don't update during override if that is disabled on the module if (PluginInfo.Instance is Module module) { if (module.IsActivatedOverride && !module.UpdateDuringActivationOverride) return; } _lastEvent = DateTime.Now; _timer = new Timer(Interval.TotalMilliseconds); _timer.Elapsed += TimerOnElapsed; _timer.Start(); } } /// /// Stops calling the at the configured /// Note: Called automatically when the plugin disables /// public void Stop() { lock (this) { if (_timer == null) return; _timer.Elapsed -= TimerOnElapsed; _timer.Stop(); _timer.Dispose(); _timer = null; } } private void TimerOnElapsed(object sender, ElapsedEventArgs e) { if (!PluginInfo.Instance.Enabled) return; var interval = DateTime.Now - _lastEvent; _lastEvent = DateTime.Now; Action(interval.TotalSeconds); } private void InstanceOnPluginEnabled(object? sender, EventArgs e) { Start(); } private void InstanceOnPluginDisabled(object? sender, EventArgs e) { Stop(); } } }