温馨提示×

linux c++怎么实现定时器

小樊
44
2026-09-29 05:58:32
栏目: 编程语言

在 Linux 下用 C++ 实现定时器,常见有几种方案,从“最简单”到“最专业”依次如下。你可以根据使用场景选择。


一、最基础:sleep / usleep(不推荐做定时器)

适合简单延时,不适合精确或并发定时器。

#include <unistd.h>
#include <iostream>

int main() {
    while (true) {
        std::cout << "tick" << std::endl;
        sleep(1); // 1秒
    }
}

❌ 缺点:阻塞线程,无法管理多个定时器


二、POSIX 定时器(推荐:精准、内核级)

使用 <timer.h> 的 timer_create

示例:每 1 秒触发一次

#include <iostream>
#include <signal.h>
#include <time.h>

void timer_handler(int sig) {
    std::cout << "timer fired" << std::endl;
}

int main() {
    struct sigaction sa;
    sa.sa_flags = 0;
    sa.sa_handler = timer_handler;
    sigaction(SIGRTMIN, &sa, nullptr);

    timer_t timerid;
    struct sigevent sev{};
    sev.sigev_notify = SIGEV_SIGNAL;
    sev.sigev_signo = SIGRTMIN;
    timer_create(CLOCK_REALTIME, &sev, &timerid);

    struct itimerspec its{};
    its.it_value.tv_sec = 1;     // 首次触发
    its.it_interval.tv_sec = 1;  // 周期

    timer_settime(timerid, 0, &its, nullptr);

    while (true) pause();
}

✅ 优点:

  • 高精度
  • 内核维护
  • 支持周期 / 一次性

❌ 缺点:

  • 信号处理较麻烦
  • 多线程需注意信号掩码

三、基于 std::thread + chrono(C++ 风格,简单)

适合应用层逻辑

#include <iostream>
#include <thread>
#include <chrono>

void timer_loop() {
    while (true) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << "tick" << std::endl;
    }
}

int main() {
    std::thread t(timer_loop);
    t.join();
}

✅ 优点:

  • 代码简单
  • 不需要系统调用知识

❌ 缺点:

  • 精度一般
  • 线程开销

四、使用 epoll + timerfd(高性能服务器首选 ⭐)

这是 Linux 服务端标准做法

#include <sys/timerfd.h>
#include <unistd.h>
#include <iostream>

int main() {
    int fd = timerfd_create(CLOCK_MONOTONIC, 0);

    struct itimerspec its{};
    its.it_value.tv_sec = 1;
    its.it_interval.tv_sec = 1;
    timerfd_settime(fd, 0, &its, nullptr);

    uint64_t exp;
    while (true) {
        read(fd, &exp, sizeof(exp));
        std::cout << "timer fired" << std::endl;
    }
}

✅ 优点:

  • 可纳入 epoll
  • 支持大量定时器
  • 非阻塞

✅ 适合:

  • 网络服务器
  • 事件驱动架构

五、C++ 高级封装(推荐库)

1️⃣ boost::asio::steady_timer

boost::asio::io_context io;
boost::asio::steady_timer t(io, std::chrono::seconds(1));
t.async_wait([](auto){ std::cout << "timeout\n"; });
io.run();

2️⃣ libev / libevent

  • 高性能
  • 工业级

六、方案选择建议

场景 推荐
简单脚本 sleep
精准定时 POSIX timer
服务器 timerfd + epoll
C++ 项目 asio / thread

如果你愿意,可以告诉我:

  • 是 单定时器还是多定时器
  • 是否 多线程 / 网络程序
  • 精度要求(ms / us)

我可以给你一个完整可直接用的 C++ 类。

0 踩