简体   繁体   English

如何让我的程序在每个给定时间(例如 1/s)只迭代一次?

[英]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.假设我有一个 for 循环,它从 a.txt 文件中逐行读取指令,而我希望做的是让程序每秒左右执行一次这些指令。 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:假设你想让程序等待一秒或更多秒(并且你在一个 POSIX 系统上,比如 Linux,它带来了sleep() )你可以这样做:

#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. */
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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