LinuxのTimerでスケジュールタスクを組む方法

Linuxではtimer_create関数でタイマーを作成し、timer_settime関数でタイマーの間隔やトリガー方法を設定します。

次に簡単なサンプルコードを示します。

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>

timer_t timerid;

void timer_handler(union sigval val) {
    printf("Timer expired\n");
}

int main() {
    struct sigevent sev;
    struct itimerspec its;
    int ret;

    // 创建定时器
    sev.sigev_notify = SIGEV_THREAD;
    sev.sigev_notify_function = timer_handler;
    sev.sigev_notify_attributes = NULL;
    sev.sigev_value.sival_ptr = NULL;
    ret = timer_create(CLOCK_REALTIME, &sev, &timerid);
    if (ret != 0) {
        perror("timer_create");
        exit(1);
    }

    // 设置定时器的间隔和触发方式
    its.it_interval.tv_sec = 1;  // 间隔1秒
    its.it_interval.tv_nsec = 0;
    its.it_value.tv_sec = 1;     // 1秒后开始触发
    its.it_value.tv_nsec = 0;
    ret = timer_settime(timerid, 0, &its, NULL);
    if (ret != 0) {
        perror("timer_settime");
        exit(1);
    }

    // 主循环
    while (1) {
        // 等待定时器触发
        pause();
    }

    return 0;
}

タイマー作成関数のtimer_createでタイマーを作成し、タイマーが起動したときの関数をsigev_notify_functionに指定。次にタイマーのインターバルや起動方法をtimer_settimeで設定し、pause関数を呼び出してメインループに入り、タイマーの起動を待つ。

タイマーのトリガー時にtimer_handler関数を呼び出してメッセージを出力します。

タイマーを使う際には、librtライブラリをコンパイル時にリンクしておく必要があることに注意し、 -lrt オプションでリンクします。

bannerAds