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.
I would use Job Scheduling Library like Quartz or simply create console application and run it using windows task scheduler at the specific time of the day.
Why not just use System.Timers.Timer?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With