Dispenser/DispenserCommon/Scheduler/ExecuteTask.cs

39 lines
903 B
C#
Raw Permalink Normal View History

2024-08-16 07:20:09 +00:00
namespace DispenserCommon.Scheduler;
/// <summary>
/// 通过定时执行某个委托方法
/// </summary>
public class ExecuteTask : ITask
{
private readonly Timer _timer;
public ExecuteTask(string name, Action action, int interval = 100)
{
Name = name;
Interval = interval;
Action = action;
_timer = new Timer(_ => { Run(); }, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(Interval));
}
public int Interval { get; set; }
public string Name { get; set; }
public Action Action { get; set; }
/// <summary>
/// 移除任务进行定时任务释放
/// </summary>
public void Dispose()
{
_timer.Dispose();
}
/// <summary>
/// 定义一个虚方法, 子类可以重写该方法实现具体的轮询逻辑
/// </summary>
public void Run()
{
Action.Invoke();
}
}