-2

I am making an app that is highly reliant on starting some work exactly on a given time. For example, the pseduo flow will be:

[23/02/2022 13:25:15] - Program starts and does some pre-processing
[23/02/2022 13:26:45] - Program has done pre-processing work. Program goes to sleep
[23/02/2022 13:30:00] - Program fires up and starts work

What is the most accurate way I can achieve this? I want to be able to start the work exactly on 13:30:00 (this time may change but just using as an example).

Note that I don't want to use the System Clock as I understand that isn't accurate enough for this purpose.

I do not have any code written for this so far. I'm at the research phase where I'm trying to understand / PoC the best way to achieve this.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
Sam
  • 602
  • 9
  • 21
  • What you tried so far? Any error? any issue? – Prasad Telkikar Feb 23 '22 at 13:30
  • 2
    What do you mean by _exactly_ ? seconds is easy, milliseconds should happen the vast majority of the time on systems set up correctly. Microseconds will be challenging. Anything further you'll need a real-time OS. Which is it? – Jeffrey Feb 23 '22 at 13:34
  • I hope you're not using `Thread.Sleep`... – Dai Feb 23 '22 at 13:34
  • 2
    Why wouldn't the system clock be accurate enough -- how much accuracy do you need? Unless you're hooking up an atomic clock yourself and ditch C# and Windows in favor of a language/OS combo with hard real time guarantees, there are going to be limits to accuracy one way or another. – Jeroen Mostert Feb 23 '22 at 13:35
  • 1
    Time is relative. You need an atomic clock or time crystals or a pulsar hooked up to your computer if you want to achieve that kind of precision. – Krausladen Feb 23 '22 at 13:41
  • 1
    Missing from question: The specification for the acceptable error in time measurement. – Matthew Watson Feb 23 '22 at 13:43
  • Windows and Linux are not, repeat not, real-time systems. They lack the task-scheduling guarantees to get something to run at a precise time. And they're subject to the small but nonzero inaccuracies in the Network Time Protocol. So reconsider your system design if it cannot tolerate tasks running a second or two early or late. And avoid the top and bottom of the hour: lots of jobs run at those times, and your work may contend with them. – O. Jones Feb 23 '22 at 13:45
  • 1
    Modern machines' internal system clocks are plenty accurate, more accurate than their OS task schedulers. Read up on the Network Time Protocol to learn more. – O. Jones Feb 23 '22 at 13:50

1 Answers1

1

C# may not be the optimal solution here. A scheduled task may be what you're looking for (or the equivalent for the OS the code will be running on).

Set up the task to run your program at 13:30 daily (or whatever frequency you desire).

Mike Hofer
  • 16,477
  • 11
  • 74
  • 110