Background worker check when it's midnight?

I want to create a background worker for WinForm that runs code whenever midnight fills.

I have an idea how to do this, but I am sure that this is not the best way to do this.

while(1==1) { //if Datetime.Now == midnight, execute code //sleep(1second) } 
+7
c # backgroundworker winforms
source share
6 answers

Use System.Timers.Timer and when you start the application, simply calculate the difference between DateTime.Now and DateTime.Today.AddDays(0) . Then set the interval for this amount.

Recently, I have really been doing something like this:

 public static class DayChangedNotifier { private static Timer timer; static DayChangedNotifier() { timer = new Timer(GetSleepTime()); timer.Elapsed += (o, e) => { OnDayChanged(DateTime.Now.DayOfWeek); timer.Interval = this.GetSleepTime(); }; timer.Start(); SystemEvents.TimeChanged += new EventHandler(SystemEvents_TimeChanged); } private static void SystemEvents_TimeChanged(object sender, EventArgs e) { timer.Interval = GetSleepTime(); } private static double GetSleepTime() { var midnightTonight = DateTime.Today.AddDays(1); var differenceInMilliseconds = (midnightTonight - DateTime.Now).TotalMilliseconds; return differenceInMilliseconds; } private static void OnDayChanged(DayOfWeek day) { var handler = DayChanged; if (handler != null) { handler(null, new DayChangedEventArgs(day)); } } public static event EventHandler<DayChangedEventArgs> DayChanged; } 

and

 public class DayChangedEventArgs : EventArgs { public DayChangedEventArgs(DayOfWeek day) { this.DayOfWeek = day; } public DayOfWeek DayOfWeek { get; private set; } } 

Usage: DayChangedNotified.DayChanged += ....

+21
source share

Instead, you can use a timer and set the timer tick interval as the time between Now () and midnight.

+7
source share

You can use Quartz to schedule this. It may sound like a cannon to kill a mosquito in this scenario, but this is the only planning framework I know and works great.

0
source share

Do not use the survey. Instead, configure the timer task, set it at midnight, and add an event to handle.

  TimeSpan timeBetween = DateTime.Today.AddDays(1) - DateTime.Now; System.Timers.Timer t = new System.Timers.Timer(); t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed); t.Interval = 1000 * timeBetween.Seconds; t.Start(); 
0
source share

I don’t know why voice solutions were rejected when Microsoft solved this type of problem several years ago by adding a Windows service to handle time. Just create a scheduled task to run exe. No extra overhead.

0
source share

I'm a little confused about why you need WinForm, will it work at midnight? If you only need some sorting process, use the window scheduler to start it at midnight. (In XP, but I believe that the Win server should be similar) Control Panel β†’ Scheduled Tasks β†’ Add Scheduled Task β†’ Fill Wizard. Save a lot of encoding.

0
source share

All Articles