可变时间后的点火方法 [英] Fire method after variable amount of time

查看:31
本文介绍了可变时间后的点火方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C# 构建警报器服务(Windows 服务).此服务将启动并执行一些 api 调用.根据我从调用中获得的结果和适用于该用户的设置,另一种方法将在 x 时间后触发.这种情况一直持续到用户停止服务.

I am building an alerter service (windows service) in c#. This service will start and do a few api calls. based on the result I get from the calls and the setting that apply to that user an other method will fire after x amount of time. This goes on until the user stops the service.

调用方法之间的时间可以是可变的.所以启动后第一个方法调用可以在 1 分钟之后,之后下一个调用可以在 5 分钟之后,之后的调用可以在 10 分钟之后.一切都取决于我从 API 得到的响应.

The time in between the calls to the methods can be variable. So after startup the first method call can be after 1 min, after that the next call can be after 5 min, the call after that can be after 10 min. All depends on the response I get from the API.

我一直在研究 system.timers,但我发现的每个示例都有一个固定的事件触发时间,因此不符合我的需要.

I have been looking into system.timers, but every example i find has a fixed time the event fires so that does not fit my needs.

推荐答案

使用一次性定时器,并在每次调用后重置它.我通常使用 System.Threading.Timer 为此:

Use a one-shot timer, and reset it after every call. I typically use System.Threading.Timer for this:

// When you first create the timer, set it for the initial time
Timer MyTimer = new Timer(TimerCallbackFunction, null, 60000, Timeout.Infinite);

将时间段设置为 Timeout.Infinite 可防止计时器重复计时.它只会打勾一次,然后无限期地等待,或者直到您重新启动它.

Setting the period to Timeout.Infinite prevents the timer from ticking multiple times. It'll just tick once and then wait indefinitely, or until you restart it.

在你的计时器回调中,做任何需要做的事情,然后重置计时器:

In your timer callback, do whatever needs to be done and then reset the timer:

void TimerCallbackFunction(object state)
{
    // Here, do whatever you need to do.
    // Then set the timer for the next interval.
    MyTimer.Change(newTimeoutValue, Timeout.Infinite);
}

这可以防止多个并发回调(如果您的超时值太短),还可以让您指定下一次滴答的时间.

This prevents multiple concurrent callbacks (if your timeout value is too short), and also lets you specify when the next tick will be.

这篇关于可变时间后的点火方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆