c++ - linux c++ 如何在特定时间间隔后调用函数

标签 c++ linux timer

假设我的程序中有一些函数 func(),我需要在特定延迟后调用它。到目前为止,我已经用谷歌搜索并最终得到以下代码:

#include <stdio.h>
#include <sys/time.h>   /* for setitimer */
#include <unistd.h>     /* for pause */
#include <signal.h>     /* for signal */

void func()
{
    printf("func() called\n");
}

bool startTimer(double seconds)
{
    itimerval it_val;
    double integer, fractional;

    integer = (int)seconds;
    fractional = seconds - integer;

    it_val.it_value.tv_sec = integer;
    it_val.it_value.tv_usec = fractional * 1000000;
    it_val.it_interval = it_val.it_value;

    if (setitimer(ITIMER_REAL, &it_val, NULL) == -1)
        return false;

    return true;
}

int main()
{
    if (signal(SIGALRM, (void(*)(int))func) == SIG_ERR)
    {
        perror("Unable to catch SIGALRM");
        exit(1);
    }

    startTimer(1.5);

    while(1)
        pause();

    return 0;
}

它可以工作,但问题是 settimer() 导致 func() 以 1.5 秒的间隔重复调用。而我需要的是只调用 func() 一次。 有人可以告诉我该怎么做吗?也许,我需要一些额外的参数来 settimer() ?

注意:时间间隔要准确,因为这个程序稍后会播放midi音乐。

最佳答案

除非您需要程序做其他事情,否则您可以在分配的时间内简单地休眠。​​

如果需要使用报警器,可以安装报警器一次处理。

来自手册页:

struct timeval it_interval

This is the period between successive timer interrupts. If zero, the alarm will only be sent once.

代替您的代码:

it_val.it_interval = it_val.it_value;

我会设置:

it_val.it_interval.tv_sec = 0;
it_val.it_interval.tv_usec = 0;

除了您已经设置的 it_val.it_value。您所做的是对两个结构使用相同的值,这就是您看到重复间隔的原因。

关于c++ - linux c++ 如何在特定时间间隔后调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26077080/

相关文章:

python - 在 Zorin 上安装 pip

javascript - 使用 Javascript PHP MySQL 的在线考试计时器

Java:小游戏的可变计时器

c++ - 多维 std::array

c++ - 我如何调用 dataChanged

c++ - 是否有任何标准方法可以将调试打印放入库中?

python - openSUSE:在不更改默认版本的情况下安装替代版本的 python

linux - 防止 tar 提取后创建额外文件

javascript - 如何在php中显示多个倒计时器

c++ - 关于堆对象的所有权以及 C++ 和引用传递参数