Search code examples
clinuxtimerreal-time

programming EXACT timer which calles a function in c language every x seconds


I need some help with a part of my Programm. I want to call a function EXACTLY every x seconds. The problem with the most soultions is, that the time to call the sleep() or w/e function stacks over time.

An example: If I want to call a function every second with sleep(1), it takes 1 second + a very small x (time to call the sleep() function). So it takes 1,x seconds. Not 1,0 second.

Over a long period of time the x stacks to a "huge amount" of time.

I want a code snippet which executes something EXACTLY every second so that I get exact timestamps without any additional delay. I think it's part of the real-time-programming problem.

Is there some working code out there for that?

Please help me out with that. :)

FloKL


Solution

  •  int X = 10;
     int t1 = (int)time(NULL);
     while(1==1){
         // execute your process
         ...
         // calculate next tick
         t1 = t1 + X;
         sleep(t1 - (int)time(NULL));
     }