c# - 在 Timer.Interval 上设置计数器值
问题描述
我有一个计时器,我用它来执行方法中的事件。我需要每 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;
}
}
}
}
解决方案
推荐阅读
- corda - 在 cordapp-example 和 cordapp-training-solutions 上 gradlew deployNodes 时节点启动错误期间出现异常
- c - C 语言中 Mainframe TN3270(代码页 1047,1147,500,249)上的字符串/正则表达式字符 '[', ']', '{', '}' 替换为空格
- python - 如何正确管理 Pipfile.lock
- ruby-on-rails - 为什么 Ruby on Rails 脚手架会失败
- python - Python以不同的方式解析JSON对象
- python - 我得到相反的答案,当时间为 0 -11 小时时,它正在打印晚上好
- javascript - 用于检查自定义下拉列表中的必填字段的 JQuery 函数中的错误
- reactjs - React dom 元素被加载但实际上并没有显示在浏览器中
- jquery - 在 SharePoint 2013 中使用 JQUERY 删除动态生成的 div
- php - tcpdf html 表格行超过 500 行导致空白页