本文介绍了定时器运行每5分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以运行一些功能每5分钟?例:我想运行 sendRequest将()仅在14:00,14:05,14:10等等

How can I run some function every 5th minute? Example: I want run sendRequest() only at time 14:00, 14:05, 14:10 etc.

我想这样做编程,在C#。该应用程序是一个Windows服务。

I would like to do it programmatically, in C#. The application is a Windows service.

推荐答案

是有用的。但是,恕我直言,拥有现代化的C#现在是更好地使用与工作基于API异步等待。另外,我有点不同的实施细节,比如如何管理延迟计算,以及如何在当前时间四舍五入到最近的五分钟间隔。

The answer posted six years ago is useful. However, IMHO with modern C# it is now better to use the Task-based API with async and await. Also, I differ a little on the specifics of the implementation, such as how to manage the delay computation and how to round the current time to the next five minute interval.

首先,我们假设 sendRequest将()方法的返回值无效并没有参数。那么,让我们假设的基本要求是运行它的大致的每五分钟(即它不是那么重要,它在小时五分钟师方式运行)。那么可以实现很容易,就像这样:

First, let's assume the sendRequest() method returns void and has no parameters. Then, let's assume that the basic requirement is to run it roughly every five minutes (i.e. it's not that important that it run exactly on five-minute divisions of the hour). Then that can be implemented very easily, like this:

async Task RunPeriodically(Action action, TimeSpan interval, CancellationToken token)
{
    while (true)
    {
        action();
        await Task.Delay(interval, token);
    }
}

它可以被称为是这样的:

It can be called like this:

CancellationTokenSource tokenSource = new CancellationTokenSource();

Task timerTask = RunPeriodically(sendRequest, TimeSpan.FromMinutes(5), tokenSource.Token);

tokenSource.Cancel()被调用时,循环将被打断 TaskCanceledException 在抛出的等待Task.Delay(...)语句。否则, sendRequest将()方法将每五分钟叫(它被立即调用的时候, RunPeriodically()方法被称为…你可以重新排序报表中的循环,如果你想让它等待在第一时间太)

When tokenSource.Cancel() is called, the loop will be interrupted by the TaskCanceledException thrown at the await Task.Delay(...) statement. Otherwise, the sendRequest() method will be called every five minutes (with it being called immediately when the RunPeriodically() method is called…you can reorder the statements in the loop if you want it to wait the first time too).

这是最简单的版本。相反,如果你想在五个分钟的间隔究竟执行的操作,你可以做同样的事情,但计算下一运行时间和延迟的时间适当的量。例如:

That's the simplest version. If instead you do want to perform the action exactly on five minute intervals, you can do something similar, but compute the next run time and delay for an appropriate amount of time. For example:

// private field somewhere appropriate; it would probably be best to put
// this logic into a reusable class.
DateTime _nextRunTime;

async Task RunPeriodically(Action action,
    DateTime startTime, TimeSpan interval, CancellationToken token)
{
    _nextRunTime = startTime;

    while (true)
    {
        TimeSpan delay = _nextRunTime - DateTime.UtcNow;

        if (delay > TimeSpan.Zero)
        {
            await Task.Delay(delay, token);
        }

        action();
        _nextRunTime += interval;
    }
}

这样调用:

CancellationTokenSource tokenSource = new CancellationTokenSource();
DateTime startTime = RoundCurrentToNextFiveMinutes();

Task timerTask = RunPeriodically(sendRequest,
    startTime, TimeSpan.FromMinutes(5), tokenSource.Token);

当助手方法 RoundCurrentToNextFiveMinutes()是这样的:

DateTime RoundCurrentToNextFiveMinutes()
{
    DateTime now = DateTime.UtcNow,
        result = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0);

    return result.AddMinutes(((now.Minute / 5) + 1) * 5);
}

在任一例子中,在的TimerTask 对象可用于监控循环的状态。在大多数情况下,它可能不是必要的。但是,如果你希望能够,例如等待直到code的其他部分取消循环,这个目标是你用什么。

In either example, the timerTask object can be used to monitor the state of the loop. In most cases, it's probably not needed. But if you want to be able to, e.g. await until some other part of the code cancels the loop, this object is what you'd use.

请注意, Task.Delay()方法确实在实施用一个定时器。以上不建议避免使用计时器,而是展现运用现代C#原来的目标实现的目的异步 / 等待功能。这个版本将网更干净与已经使用异步 / 等待

Note that the Task.Delay() method does use a timer in its implementation. The above is not suggested for the purpose of avoiding the use of a timer, but rather to show an implementation of the original goal using the modern C# async/await features. This version will mesh more cleanly with other code that is already using async/await.

这篇关于定时器运行每5分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:22