using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace Tango.Core.Threading { /// /// Represents an action executer with a predefined interval and a reset mechanism. /// public class ActionTimer : IDisposable { private Timer _timer; private Action _action; /// /// Initializes a new instance of the class. /// /// The interval. public ActionTimer(TimeSpan interval) { _timer = new Timer(interval.TotalMilliseconds); _timer.Enabled = true; _timer.Stop(); _timer.Elapsed += _timer_Elapsed; } /// /// Resets the current timer and replaces the action to be invoked. /// /// The action. public void ResetReplace(Action action) { if (_timer != null) { _timer.Stop(); _action = action; _timer.Start(); } } private void _timer_Elapsed(object sender, ElapsedEventArgs e) { _timer.Stop(); _action?.Invoke(); } /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// public void Dispose() { if (_timer != null) { _timer.Stop(); _timer = null; } } } }