Guest User

Untitled

a guest
Aug 10th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. C# .NET 2 Threading.Timer - time drifting
  2. public void MyTimerCallback(object something) {
  3. var now = DateTime.UtcNow;
  4. var shouldProbablyHaveRun = new DateTime(
  5. now.Year, now.Month, now.Day,
  6. now.Hour, now.Minute - (now.Minute % 10), 0);
  7. var nextRun = shouldProbablyHaveRun.AddMinutes(10.0);
  8.  
  9. // Do stuff here!
  10.  
  11. var diff = nextRun - DateTime.UtcNow;
  12. timer.Change(diff, new TimeSpan(-1));
  13. }
  14.  
  15. if (DateTime.Now.Minute % 10) == 0
  16.  
  17. while ((DateTime.Now - lastRunTime).TotalSeconds < 600)
  18. CurrentThread.Sleep(1000);
  19.  
  20. public static void Main()
  21. {
  22. System.Timers.Timer aTimer = new System.Timers.Timer();
  23. aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
  24. // Set the Interval to 600 seconds.
  25. aTimer.Interval=600000;
  26. aTimer.Enabled=true;
  27.  
  28. Console.WriteLine("Press 'q' to quit the sample.");
  29. while(Console.Read()!='q');
  30. }
  31.  
  32. // Specify what you want to happen when the Elapsed event is raised.
  33. private static void OnTimedEvent(object source, ElapsedEventArgs e)
  34. {
  35. Console.WriteLine("10 minutes passed!");
  36. }
Add Comment
Please, Sign In to add comment