POSIX创建、初始化以及删除一个定时器的行动被分为三个不同的函数:timer_create()(创建定时器)、timer_settime()(初始化定时器)以及timer_delete(销毁它)
一个典型的例子如:
#include <sys/time.h>
timer_t fade_in_timer;
int myclass::starttimer()
{
struct sigevent evp;
memset(&evp, 0, sizeof(evp));
evp.sigev_value.sival_ptr = this; //这里传一个参数进去,在timer的callback回调函数里面可以获得它
evp.sigev_notify = SIGEV_THREAD; //定时器到期后内核创建一个线程执行sigev_notify_function函数
evp.sigev_notify_function = fade_in_callback; //这个就是指定回调函数
int ret = 0;
ret = timer_create(CLOCK_REALTIME, &evp, &fade_in_timer);
if(ret < 0)
{
printf("timer_create() fail, ret:%d", ret);
return ret;
}
struct itimerspec ts;
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 200000000; //200ms
ts.it_value.tv_sec = 0;
ts.it_value.tv_nsec = 200000000; //200ms
ret = timer_settime(fade_in_timer, TIMER_ABSTIME, &ts, NULL);
if(ret < 0)
{
printf("timer_settime() fail, ret:%d", ret);
timer_delete(fade_in_timer);
timer_created = false;
return ret;
}
return 0;
}
/*static*/void myclass::fade_in_callback(union sigval v)
{
//v.sival_ptr 就是创建timer时传进来的指针,最后在合适的地方删除一下timer
myclass *ptr = (myclass*)v.sival_ptr;
timer_delete(audiotrack->fade_in_timer);
}
使用timer时注意两点:
1.回调函数如果不是C函数而是类的成员函数,则不能用普通成员函数,必须用静态成员函数,因为普通成员函数含有隐含参数--this指针
2.timer定时的时间间隔,第一次是ts.it_value这么长,后面每次时间间隔是ts.it_interval这么长
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 200000000; //200ms
ts.it_value.tv_sec = 0;
ts.it_value.tv_nsec = 200000000; //200ms
参考:
http://www.kernel.org/doc/man-pages/online/pages/man2/timer_create.2.html