linux C++ 定时器代码:
#include <iostream> #include <sys/time.h> #include <signal.h> using namespace std; /* union sigval { int sival_int; //integer value void *sival_ptr; //pointer value }; struct sigevent { int sigev_notify; //notification type int sigev_signo; //signal number union sigval sigev_value; //signal value void (*sigev_notify_function)(union sigval); pthread_attr_t *sigev_notify_attributes; }; */ void func(union sigval v){ cout << "echo" << endl; } int main(){ timer_t timer; struct sigevent evp; memset(&evp, 0, sizeof(evp)); evp.sigev_value.sival_ptr = &timer; evp.sigev_notify = SIGEV_THREAD; evp.sigev_notify_function = func; evp.sigev_signo = 0; timer_create(CLOCK_REALTIME, &evp, &timer); // it_value 一定要设置,不能为0 struct itimerspec ts; ts.it_interval.tv_sec = 3; ts.it_interval.tv_nsec = 0; //200ms ts.it_value.tv_sec = 1; ts.it_value.tv_nsec = 0; //200ms timer_settime(timer, TIMER_ABSTIME, &ts, NULL); while(1); return 0; }