如何使我的程序每给定时间只迭代一次(如1s)?

问题描述 投票:2回答:1

比如说,我有一个for循环,它从一个.txt文件中逐行读取指令,我想做的是让程序每隔一秒左右执行一次这些指令。我怎样才能做到这一点呢?

下面是我的循环的代码。

  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");
    }
  }

请忽略变量名,这只是为了简化。

c for-loop timer scheduled-tasks
1个回答
2
投票

让程序每隔一秒左右执行一次这些指令。

让它等到规定的时间过去。

假设你想让程序等待一秒或多秒(而且你是在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. */
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.