我有一个计时器,我用它来执行方法中的事件。我需要每 5 分钟运行一次,但需要在计时器在 10 分钟时滴答作响时更改计数器值,然后再次重置计数器。
因此,当计时器执行超过 5,15 或 25 分钟时,我需要将计数器值设置为 1。在 10、20 或 30 分钟间隔时,我需要将其设置为 2。因此,简而言之,默认计数器值为当执行时间是 10 的倍数时始终为 2,然后再次重置为默认值。
我应该如何在 System.Timers 上做到这一点?
这是我到目前为止所拥有的:
使用 System.Timers;
namespace Demo
{
public class SampleWorker
{
private Timer timer = new System.Timers.Timer();
private bool _timerInUse = false;
private double _timerFrequency = 300000;
private int _counter = 1;
public void Main()
{
StartTimer();
}
private async void StartTimer()
{
try
{
timer.Elapsed += new ElapsedEventHandler(this.TriggerEvent);
timer.Interval = _timerFrequency; //5 mins
timer.Enabled = true;
// when timer runs with units as 5 set _counter to 2 else keep 1
}
catch (Exception ex)
{
//log exception
}
}
private async void TriggerEvent(object source, ElapsedEventArgs e)
{
if (_timerInUse == false)
{
_timerInUse = true;
try
{
Foo(_counter);
}
catch (Exception ex)
{
//log exception
}
_timerInUse = false;
}
}
}
}