Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to start a thread at a specific time [duplicate]

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);

like image 653
Bob Avatar asked Sep 04 '13 10:09

Bob


2 Answers

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.

like image 51
Sriram Sakthivel Avatar answered Sep 27 '22 17:09

Sriram Sakthivel


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?

  • Timers have no persistence mechanism.
  • Timers have inflexible scheduling (only able to set start-time & repeat interval, nothing based on dates, time of day, etc.
  • Timers don't utilize a thread-pool (one thread per timer)
  • Timers have no real management schemes - you'd have to write your own mechanism for being able to remember, organize and retreive your tasks by name, e
like image 29
Damith Avatar answered Sep 27 '22 17:09

Damith