using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace WindowsFormsAppTimer.Core { public class TimerHelper { /// /// How long between intervals, currently 30 minutes /// public static int Interval = 1000 * 60 * 30; private static Timer _workTimer; public static ActionContainer ActionContainer; /// /// Text to display to listener /// /// text public delegate void MessageHandler(string message); /// /// Optional event /// public static event MessageHandler Message; /// /// Flag to determine if timer should initialize /// public static bool ShouldRun { get; set; } = true; /// /// Default initializer /// private static void Initialize() { if (!ShouldRun) return; _workTimer = new Timer(Dispatcher); _workTimer.Change(Interval, Timeout.Infinite); } /// /// Initialize with time to delay before triggering /// /// private static void Initialize(int dueTime) { if (!ShouldRun) return; Interval = dueTime; _workTimer = new Timer(Dispatcher); _workTimer.Change(Interval, Timeout.Infinite); } /// /// Trigger work, restart timer /// /// private static void Dispatcher(object e) { Worker(); _workTimer.Dispose(); Initialize(); } /// /// Start timer without an /// public static void Start() { Initialize(); Message?.Invoke("Started"); } /// /// Start timer with an /// public static void Start(Action action) { ActionContainer = new ActionContainer(); ActionContainer.Action += action; Initialize(); Message?.Invoke("Started"); } /// /// Stop timer /// public static void Stop() { _workTimer.Dispose(); Message?.Invoke("Stopped"); } /// /// If is not null trigger action /// else alter listeners it's time to perform work in caller /// private static void Worker() { Message?.Invoke("Performing work"); ActionContainer?.Action(); } } }