在Linux系統中,可以使用timerfd
接口或者Cron
任務來實現精確的時間控制。下面分別介紹這兩種方法:
timerfd
接口timerfd
是Linux內核提供的一種計時器接口,可以用于實現精確的時間控制。以下是一個簡單的示例:
timerfd
??梢酝ㄟ^以下命令檢查:grep CONFIG_TIMERFD /boot/config-$(uname -r)
如果輸出中包含CONFIG_TIMERFD=y
,則表示支持timerfd
。
timerfd
實現定時器功能:#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/timerfd.h>
#include <time.h>
int main() {
int timer_fd = timerfd_create(CLOCK_MONOTONIC, 0);
if (timer_fd == -1) {
perror("timerfd_create");
exit(EXIT_FAILURE);
}
struct itimerspec new_value;
new_value.it_value.tv_sec = 5; // 設置定時器首次觸發的時間(秒)
new_value.it_value.tv_nsec = 0;
new_value.it_interval.tv_sec = 5; // 設置定時器重復觸發的時間間隔(秒)
new_value.it_interval.tv_nsec = 0;
if (timerfd_settime(timer_fd, 0, &new_value, NULL) == -1) {
perror("timerfd_settime");
exit(EXIT_FAILURE);
}
uint64_t expirations;
read(timer_fd, &expirations, sizeof(expirations));
printf("Timer expired %llu times\n", expirations);
close(timer_fd);
return 0;
}
gcc timerfd_example.c -o timerfd_example
./timerfd_example
Cron
任務Cron
是Linux系統中用于定期執行任務的守護進程。通過編輯crontab
文件,可以設置定時任務。以下是一個簡單的示例:
crontab
文件:crontab -e
/path/to/your/script.sh
腳本:*/5 * * * * /path/to/your/script.sh
Cron
將自動加載新的crontab
配置,并按照設定的時間執行任務。注意:Cron
任務的精度受系統負載和其他因素影響,可能無法達到毫秒級精度。如果需要更高精度的時間控制,建議使用timerfd
接口。