C#:如何启动一个线程在特定的时间线程、时间、在特定

2023-09-03 03:15:02 作者:習慣ろ沉默

我如何开始在每天的特定时间在后台线程,说下午4点?

How can I start a background thread at a specific time of day, say 16:00?

所以,当应用程序启动的线程会等到那个时候。但是,如果应用程序在此时间之后启动,然后该线程就会立即运行

So when the apps starts up the thread will wait until that time. But if the app starts up after that time then the thread will run straight away

ThreadPool.QueueUserWorkItem(MethodtoRunAt1600);

推荐答案

您可以设置定时器在 16:00 。我在这里回答过类似的问题。 这将帮助你肯定的。

You can set up a timer at 16:00. I've answered a similar question here. That should help you for sure.

private System.Threading.Timer timer;
private void SetUpTimer(TimeSpan alertTime)
{
     DateTime current = DateTime.Now;
     TimeSpan timeToGo = alertTime - current.TimeOfDay;
     if (timeToGo < TimeSpan.Zero)
     {
        return;//time already passed
     }
     this.timer = new System.Threading.Timer(x =>
     {
         this.SomeMethodRunsAt1600();
     }, null, timeToGo, Timeout.InfiniteTimeSpan);
}

private void SomeMethodRunsAt1600()
{
    //this runs at 16:00:00
}

然后用它设置

Then set it up using

SetUpTimer(new TimeSpan(16, 00, 00));

编辑:保持的定时器的参考,因为它是受垃圾收集无论定时器处于活动状态

Keep the reference of the Timer as it's subject to garbage collection irrespective of the Timer is active or not.