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

Time:12-19

I have a code with which I am reading in 35ms interval the current and position values of a machines CNC axis from a remote computer.

The data is read form the CNC/PLC comtrol 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 a 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 35ms period. It seems to work but I am not sure if this is the best way. Is there a more precise method then 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
    }

CodePudding user response:

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.

CodePudding user response:

The timer accepts a direct callback method. If you want to execute something periodic, it can be done as follows:

var timer = new Timer(TimerCallback, state, startAfterTimeSpan, repeatTimeSpan);

Where you can e.g. write a method

private void TimerCallback(object state)
{
    // do something
}
  • Related