Search code examples
c#timerperiodic-task

How can I execute a code in C# (Windows Service) periodically in the most precise way?


I have a code with which I am reading in 35ms intervals the current and position values of a machine's CNC axis from a remote computer.

The data is read from the CNC/PLC control system of the machine

My C# code has to run on our company server with Windows Server 2019. I am sending the data to Kafka, our AI experts have to interpret the current and position curve shapes for an AI algorithm. So the data has to be read every 35 ms as precise as possible

Normally I have used first a system timer with a 35ms period. It seems to work but I am not sure if this is the best way. Is there a more precise method than using a system timer?

My code

 public void Main()
 {
 InitializeTimer_1();
 }
  public void InitializeTimer_1()
    {
        System.Timers.Timer timer1 = new System.Timers.Timer();
        timer1.Elapsed += new ElapsedEventHandler(OnTimedEvent1);
        timer1.Interval = 35;
        timer1.Enabled = true;
    }

  public void OnTimedEvent1(object sender, EventArgs e)
    {
        // my Data reading code
    }

Solution

  • There are multiple ways to solve this problem.

    It first depends on what kind of application you have.

    If you have a console app then you can schedule it to run every 35ms using the windows task scheduler and it will work.

    If it is a long-running process like windows service then you can use the same code you have

    There is one very useful library hangfire, you can explore this as well.

    Also, refer to this post as well, you may get more directions.

    Edit: System.Timers.Timer is sufficient for most the purpose, you could also consider System.Threading.Timer for short intervals, it allows more precise timings but its will run on a separate thread so keep that in mind. There is one more option System.Diagnostics.Stopwatch which has more high precision than other approaches.

    The actual precision of the timer also depends on hardware, OS and the workload on the machine.

    Now you can evaluate all the approaches and chose the best one for you.