可变时间后的点火方法
Fire method after variable amount of time
我正在用 C# 构建警报器服务(windows 服务)。此服务将启动并进行一些 api 调用。根据我从调用中获得的结果和适用于该用户的设置,另一种方法将在 x 时间后触发。这种情况一直持续到用户停止服务。
方法调用之间的时间可以是可变的。所以启动后第一个方法调用可以在 1 分钟后,下一个调用可以在 5 分钟后,再下一个调用可以在 10 分钟后。一切都取决于我从 API.
得到的回应
我一直在研究 system.timers,但我发现的每个示例都有固定的事件触发时间,因此不符合我的需要。
全局定义时间变量并在每次响应后重置间隔时间
仅供参考
1 Minute = 60000 so for 10 Minutes aTimer.Interval=60000 * 10;
像这样使用它
//defined globally
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
//api call goes here
aTimer.Interval=5000; // here you can define the time or reset it after each api call
aTimer.Enabled=true;
使用一次性计时器,并在每次调用后重置它。我通常为此使用 System.Threading.Timer:
// When you first create the timer, set it for the initial time
Timer MyTimer = new Timer(TimerCallbackFunction, null, 60000, Timeout.Infinite);
将周期设置为 Timeout.Infinite
可防止计时器多次计时。它只会勾选一次,然后无限期地等待,或者直到您重新启动它。
在您的计时器回调中,执行任何需要完成的操作,然后重置计时器:
void TimerCallbackFunction(object state)
{
// Here, do whatever you need to do.
// Then set the timer for the next interval.
MyTimer.Change(newTimeoutValue, Timeout.Infinite);
}
这可以防止多个并发回调(如果您的超时值太短),还可以让您指定下一次报价的时间。
我正在用 C# 构建警报器服务(windows 服务)。此服务将启动并进行一些 api 调用。根据我从调用中获得的结果和适用于该用户的设置,另一种方法将在 x 时间后触发。这种情况一直持续到用户停止服务。
方法调用之间的时间可以是可变的。所以启动后第一个方法调用可以在 1 分钟后,下一个调用可以在 5 分钟后,再下一个调用可以在 10 分钟后。一切都取决于我从 API.
得到的回应我一直在研究 system.timers,但我发现的每个示例都有固定的事件触发时间,因此不符合我的需要。
全局定义时间变量并在每次响应后重置间隔时间
仅供参考
1 Minute = 60000 so for 10 Minutes aTimer.Interval=60000 * 10;
像这样使用它
//defined globally
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
//api call goes here
aTimer.Interval=5000; // here you can define the time or reset it after each api call
aTimer.Enabled=true;
使用一次性计时器,并在每次调用后重置它。我通常为此使用 System.Threading.Timer:
// When you first create the timer, set it for the initial time
Timer MyTimer = new Timer(TimerCallbackFunction, null, 60000, Timeout.Infinite);
将周期设置为 Timeout.Infinite
可防止计时器多次计时。它只会勾选一次,然后无限期地等待,或者直到您重新启动它。
在您的计时器回调中,执行任何需要完成的操作,然后重置计时器:
void TimerCallbackFunction(object state)
{
// Here, do whatever you need to do.
// Then set the timer for the next interval.
MyTimer.Change(newTimeoutValue, Timeout.Infinite);
}
这可以防止多个并发回调(如果您的超时值太短),还可以让您指定下一次报价的时间。