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);
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));
Edit: Keep the reference of the Timer as it's subject to garbage collection irrespective of the Timer is active or not.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加