Created
March 5, 2017 20:50
-
-
Save NiclasOlofsson/fc4932dab6e33d06b6c4bb8e367b99c5 to your computer and use it in GitHub Desktop.
A cooldown timer for MiNET plugins.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace MiNET.GameFramework.Plugin.Utils | |
{ | |
public class CooldownTimer | |
{ | |
public TimeSpan TimeSpan { get; private set; } | |
public DateTime ClearingTime { get; private set; } | |
public CooldownTimer(long timeSpan) : this(new TimeSpan(timeSpan*TimeSpan.TicksPerMillisecond)) | |
{ | |
} | |
public CooldownTimer(TimeSpan timeSpan) | |
{ | |
TimeSpan = timeSpan; | |
Reset(); | |
} | |
public void Reset() | |
{ | |
ClearingTime = DateTime.UtcNow.Add(TimeSpan); | |
} | |
public bool CanExecute() | |
{ | |
return ClearingTime <= DateTime.UtcNow; | |
} | |
public bool Execute() | |
{ | |
if (!CanExecute()) | |
{ | |
return false; | |
} | |
Reset(); | |
return true; | |
} | |
} | |
public class CooldownTimerAction<T> : CooldownTimer where T : class | |
{ | |
public Action<T> CallBackAction { get; set; } | |
public CooldownTimerAction(long timeSpan, Action<T> callbackAction) : this(new TimeSpan(timeSpan*TimeSpan.TicksPerMillisecond), callbackAction) | |
{ | |
} | |
public CooldownTimerAction(TimeSpan timeSpan, Action<T> callbackAction) : base(timeSpan) | |
{ | |
CallBackAction = callbackAction; | |
} | |
public bool Execute(T param) | |
{ | |
if (!CanExecute()) | |
{ | |
return false; | |
} | |
CallBackAction?.Invoke(param); | |
Reset(); | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment