POSIX timer

https://www.cnblogs.com/LubinLew/p/POSIX-Timer.html

例子2:循环timer,使用绝对时间

#include <signal.h>    /* union sigval / struct sigevent */
#include <stdio.h>    /* printf */
#include <string.h>    /* memset */
#include <unistd.h> /* sleep */
#include <time.h>

#define printf_with_time(format, ...)                                        \
{                                                                            \
    struct timespec spec;                                                    \
    clock_gettime(CLOCK_MONOTONIC, &spec);                                    \
    printf("[%lu:%lu]"format"\n", spec.tv_sec, spec.tv_nsec, ##__VA_ARGS__);\
}


void timer_notify_cb(union sigval val)
{
    printf_with_time("timer expiration");

}

int main(void)
{
    /* Variable Definition */
    timer_t id;
    struct timespec spec;
    struct sigevent ent;
    struct itimerspec value;
    struct itimerspec get_val;

    /* Init */
    memset(&ent, 0x00, sizeof(struct sigevent));
    memset(&get_val, 0x00, sizeof(struct itimerspec));
    
    /* create a timer */
    ent.sigev_notify = SIGEV_THREAD;
    ent.sigev_notify_function = timer_notify_cb;
    printf_with_time("create timer");
    timer_create(CLOCK_REALTIME, &ent, &id);        /* CLOCK_REALTIME */

    /* start a timer */
    clock_gettime(CLOCK_REALTIME, &spec);            /* CLOCK_REALTIME */
    value.it_value.tv_sec = spec.tv_sec + 2;
    value.it_value.tv_nsec = spec.tv_nsec + 0;
    value.it_interval.tv_sec = 1;    /* per second */
    value.it_interval.tv_nsec = 0;
    printf_with_time("start timer");
    timer_settime(id, TIMER_ABSTIME, &value, NULL); /* TIMER_ABSTIME */

    sleep(10);
    printf_with_time("delete timer");
    timer_delete(id);
    return 0;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值