简体   繁体   中英

How do I make my program iterate only once every given time (ex 1/s)?

Let's say that for example I have a for loop which is reading instructions line by line from a.txt file and what I wish to do is make the program execute those instructions once every second or so. How can I possibly do this?

Here's the code for my loop:

  for(j = 0; j < PC; j++) {             
    txtfilepointer = fopen(listWithTxtFilesToRead[j].name, "r");

    while (fscanf(txtfilepointer, "%c %s", &field1, field2) != EOF ) {

      // here it should be executing the given instruction every second or so...

      printf("whatever the instruction told me to do");
    }
  }

Please ignore the variable names, it's just for examplifying.

make the program execute those instructions once every second or so

Make it wait until the required time passed.

Assuming you want to have the program wait for one or more seconds (and you are on a POSIX system, like Linux, which brings sleep() ) you can do this like so:

#include <time.h> /* for time() */
#include <unistd.h> /* for sleep() */

#define SECONDS_TO_WAIT (3) 

...

  {
    time_t t = time(NULL);

    /* Instructions to execute go here. */

    while ((time(NULL) - t) < SECONDS_TO_WAIT)
    {
      sleep(1); /* Sleep (wait) for one second. */
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM