定期调用功能,而无需使用线程和sleep()方法在C [英] Call function periodically without using threads and sleep() method in c

查看:125
本文介绍了定期调用功能,而无需使用线程和sleep()方法在C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要调用一个函数,可以说每10秒或20秒。当我搜索,我想出了线程和睡眠()方法无处不在。

I want to call a function, lets say every 10 or 20 seconds. When I searched, I came up with threads and sleep() method everywhere.

我也查在C时间和时钟类,但我找不到任何有用具体到我的问题。

I also checked for time and clock classes in C but I could not find anything helpful specific to my question.

什么是最简单的方式来定期调用函数?

What is the most simple way to call functions periodically?

推荐答案

使用的libevent ,在我看来,是清洁的解决方案,因为在此期间,你可以做其它操作(甚至其他定时功能)

Use libevent, in my opinion, is the cleaner solution because, in the meantime, you can do other operations (even other timed functions)

看看这个简单和自我解释的例子,打印出的Hello每3秒:

look at this simple and self explaining example that print out Hello every 3 seconds:

#include <stdio.h>
#include <sys/time.h>
#include <event.h>

void say_hello(int fd, short event, void *arg)
{
  printf("Hello\n");
}

int main(int argc, const char* argv[])
{
  struct event ev;
  struct timeval tv;

  tv.tv_sec = 3;
  tv.tv_usec = 0;

  event_init();
  evtimer_set(&ev, say_hello, NULL);
  evtimer_add(&ev, &tv);
  event_dispatch();

  return 0;
}

这篇关于定期调用功能,而无需使用线程和sleep()方法在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆