timerfd 周期性任务
Timerfd Periodic Task
题目详情
低延迟交易系统依赖精确任务调度维持连接健康和发送心跳,不阻塞关键执行线程。使用 Linux 的 timerfd 配合 epoll 实现异步周期性任务处理。
任务:实现周期性任务调度器类,使用 timerfd 创建定时器文件描述符,配置周期,通过 epoll 异步等待定时器触发。触发后执行心跳或连接检查。
英文原题
Low-latency trading systems rely on precise task scheduling to maintain connection health and transmit heartbeats without blocking critical execution threads. Utilizing Linux system calls like timerfd combined with epoll enables asynchronous handling of periodic events alongside network sockets, minimizing jitter and ensuring high responsiveness in event-driven gateways.
Task
Implement the PeriodicScheduler class to manage periodic events using Linux system calls. The run method must create a m
解析
问题分析
timerfd 将定时器抽象为文件描述符,可融入 epoll 事件循环。相比 signal/timer_create,timerfd 避免了异步信号带来的重入问题,更适合事件驱动架构。
实现
class PeriodicTimer {
int fd_;
public:
PeriodicTimer(std::chrono::milliseconds interval) {
fd_ = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
itimerspec ts{};
ts.it_interval = ts.it_value = {0, (long)(interval.count() * 1000000)};
::timerfd_settime(fd_, 0, &ts, nullptr);
}
int fd() const { return fd_; }
bool expired() const {
uint64_t expirations;
return ::read(fd_, &expirations, sizeof(expirations)) > 0; // 非阻塞
}
~PeriodicTimer() { ::close(fd_); }
};复杂度与边界
- 时间复杂度:expired O(1)
- 空间复杂度:O(1)
- 边界条件:(1) 定时精度受系统 tick 限制 (2) 系统挂起期间不触发 (3) 需配合 epoll 使用
英文解析
Analysis
timerfd abstracts timers as file descriptors, enabling integration with epoll event loops. Compared to signal/timer_create, timerfd avoids reentrancy issues from asynchronous signals, making it better suited for event-driven architectures.
Solution
class PeriodicTimer {
int fd_;
public:
PeriodicTimer(std::chrono::milliseconds interval) {
fd_ = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
itimerspec ts{};
ts.it_interval = ts.it_value = {0, (long)(interval.count() * 1000000)};
::timerfd_settime(fd_, 0, &ts, nullptr);
}
int fd() const { return fd_; }
bool expired() const {
uint64_t expirations;
return ::read(fd_, &expirations, sizeof(expirations)) > 0; // Non-blocking
}
~PeriodicTimer() { ::close(fd_); }
};Complexity & Edge Cases
- Time complexity: expired O(1)
- Space complexity: O(1)
- Edge cases: (1) Timer precision limited by system tick resolution (2) Does not fire during system suspend (3) Must be used with epoll
Verification
Create periodic timer, integrate with epoll loop. Verify consistent interval firing. Test that read() correctly counts missed expirations.
Key Considerations
timerfd enables unified event-loop integration of timers alongside I/O events. In trading systems, periodic tasks (risk checks, PnL snapshots, heartbeat) all use timerfd descriptors monitored by the same epoll loop, eliminating the need for separate timer threads.