C#:如何启动一个线程在特定的时间 [英] C#: How to start a thread at a specific time

查看:507
本文介绍了C#:如何启动一个线程在特定的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何开始在每天的特定时间在后台线程,说下午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.

这篇关于C#:如何启动一个线程在特定的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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