检查这是否有帮助:
public class Repeater
{
private readonly List<DateTime> _checkpoints;
private readonly Action _action;
private readonly Func<Task> _asyncAction;
private readonly Timer _timer;
private Thread _processingThread;
public Repeater(List<DateTime> checkpoints, Action action)
{
_checkpoints = checkpoints;
_timer = new Timer
{
AutoReset = false,
Enabled = false
};
_timer.Elapsed += TimerCheckpoint_Elapsed;
_timer.Elapsed += CalculateNextExecution;
_action = action;
_asyncAction = null;
}
public Repeater(List<DateTime> checkpoints, Func<Task> action)
{
_checkpoints = checkpoints;
_timer = new Timer
{
AutoReset = false,
Enabled = false
};
_timer.Elapsed += TimerCheckpoint_Elapsed;
_timer.Elapsed += CalculateNextExecution;
_asyncAction = action;
_action = null;
}
public void Start()
{
ReinitializeTimer();
}
public void Stop()
{
//_thrProcessaCheckpoints?.Abort();
_timer?.Stop();
_timer?.Dispose();
}
private void TimerCheckpoint_Elapsed(object sender, ElapsedEventArgs e)
{
if (_processingThread != null && _processingThread.IsAlive) return;
_processingThread = new Thread(async () => await ThreadStart())
{
IsBackground = true,
Name = "Timer Processing Thread"
};
try { _processingThread.Start(); } catch { /* ignored */ }
}
private async Task ThreadStart()
{
if (_asyncAction == null)
_action();
else
await _asyncAction();
}
private void CalculateNextExecution(object sender, ElapsedEventArgs e)
{
ReinitializeTimer();
}
private void ReinitializeTimer()
{
_timer.Interval = CalculateNextInterval(_checkpoints);
_timer.Start();
}
private static double CalculateNextInterval(List<DateTime> checkpoints)
{
double min = double.MaxValue;
var dateTime = DateTime.Now;
// Calculate how much time is left to the next checkpoint
foreach (var date in checkpoints)
{
TimeSpan timeForNextCheckpoint;
// If it's in the same time, calculate how much time is left
if (date.TimeOfDay > dateTime.TimeOfDay)
timeForNextCheckpoint = date.TimeOfDay - dateTime.TimeOfDay;
// If not, calculate how much time is left, counting a day
else
timeForNextCheckpoint = TimeSpan.FromHours(24) - (dateTime.TimeOfDay - date.TimeOfDay);
if (Math.Abs(timeForNextCheckpoint.TotalMilliseconds) < min)
{
min = Math.Abs(timeForNextCheckpoint.TotalMilliseconds);
}
}
return min;
}
}
用法:
var myRepeater = new Repeater(new List<DateTime>{ new DateTime(2020,19,11, 19, 55, 00) }, () => MyMethodCall());
myRepeater.Start(); // call on your application start
myRepeater.Stop(); // call on your application stop
您只需要提供包含您的任务需要执行的小时数的日期时间列表,以及将在该时间执行的方法。构造函数还有一个重载,可以在需要时接收异步方法。
var myAsyncRepeater = new Repeater(_cfg.ConfiguracaoBaixaAdiamentos.Checkpoints,
async () => await MyMethodCallAsync());