Search code examples
ctimeraspberry-pimodbus

Have a function run for a specific amount of time in C


I need to be able to run a piece of code for x amount of seconds and then stop. Something like

while(timeElapsed < setTime){
     do whatever
}

If someone is curious, what is we're trying to do here is having the program poll an indicator via modbus for a certain amount of seconds, set by the user.So I'm having an input field for the user to set the time the polling function should be running in a loop. This will be done on a raspberry pi, by the way.


Solution

  • One way is to include time.h header and use difftime function. It will be implemented to check if the elaspsed time reaches the set time.

    example:

    #include <time.h>
    
    void func(float delayInSeconds) {
        time_t startTime;
        time_t now;
        float elapsedTime;
        float setTime = delayInSeconds;
    
        time(&startTime);
        while (elapsedTime < setTime) {
            //do something...
    
            now = time(NULL);
            elapsedTime = difftime(now, startTime);
        }
    }