每30秒执行一次代码

我有一台服务器需要从客户端收集信息。 信息是一个随机数,我存储在一个频率数组中。 服务器应该告诉所有客户最常用的号码,但每30秒左右。 发送该号码的客户端将断开连接并为新号码腾出空间。 因此,数组中会添加新数字。

如何让服务器每30秒进行一次检查并发送消息?

我在Unix下工作,而不是C ++。

尝试以下伪代码逻辑:

while (TRUE) { //this can be your main loop //get current time and if more than 30 seconds after last send { //get most frequent number //inform clients //get current time and store timestamp as last send } 

}

使用闹钟()

  void handler(int signum) { ///your logic alarm(30); } int main(void) { signal(SIGALRM, handler); alarm(30); getchar(); return 0; } 

尝试使用POSIX每进程计时器: http : //man7.org/linux/man-pages/man2/timer_create.2.html在示例部分中,有一个示例每100ns调用一次计时器。

你可以简单地使用这些function:

  int nanosleep(const struct timespec *req, struct timespec *rem); or usleep(microseconds); 

这些函数使程序hibernatex秒

例如:

 while(1) { function(); //function to run each 30 sec usleep(30*1000000); }