方法,该方法在新分钟开始时运行

本文关键字:方法 分钟 开始时 运行 新分钟 | 更新日期: 2023-09-27 18:02:34

我有一个每分钟运行一次的函数:

var waitHandle = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(
    waitHandle,
    // Method to execute
    (state, timeout) =>
    {
        Console.WriteLine(DateTime.Now + " START");
        ..some stuff
        Console.WriteLine(DateTime.Now + " END");
    },
    null,
    TimeSpan.FromMinutes(1),
    false
);
这段代码执行得很好,但是示例输出是:
2016-08-16 18:45:55 START
2016-08-16 18:45:55 END
2016-08-16 18:46:55 START
2016-08-16 18:46:55 END

(或调用时它恰好在的任何秒)我希望它像这样运行:

2016-08-16 18:45:00 START
2016-08-16 18:45:00 END
2016-08-16 18:46:00 START
2016-08-16 18:46:00 END

所以我想让这个函数每分钟运行一次,但是当秒为0时。我该怎么做呢?

方法,该方法在新分钟开始时运行

显然,问题在于必须添加到代码中的初始偏移量。这很容易做到,基于serhiyb链接的问题的第二个答案:

void Register(AutoResetEvent waitHandle, TimeSpan timeout, 
    WaitOrTimerCallback callback, bool once)
{
    ThreadPool.RegisterWaitForSingleObject(waitHandle, callback, null, timeout, once);
}
void Callback(object state, bool isTimeout)
{
    Console.WriteLine(DateTime.Now + " START");
    //..some stuff
    Console.WriteLine(DateTime.Now + " END");
}

然后:

var waitHandle = new AutoResetEvent(false);
Register(
    waitHandle,
    TimeSpan.FromSeconds(60 - DateTime.Now.Second), //initial offset
    (state, isTimeout) =>
    {
        Callback(state, isTimeout);
        Register(waitHandle, TimeSpan.FromMinutes(1), Callback, false);
    },
    true);