#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
void task(union sigval value) {
// 在这里执行您的任务
timer_t *timer = value.sival_ptr;
printf("任务正在执行...\n");
// 打印当前实际按计时器的值
time_t currTime = time(NULL);
printf("当前实际时间:%s", ctime(&currTime));
// 销毁定时器
timer_delete(*timer);
free(timer);
}
void start_timer(void handler(union sigval), int sed) {
// 创建定时器
timer_t *timer = (timer_t *) malloc(sizeof(timer_t));
struct sigevent sev;
struct itimerspec its;
// 设置定时器事件
sev.sigev_notify = SIGEV_THREAD;
sev.sigev_notify_function = task;
sev.sigev_value.sival_ptr = timer;
sev.sigev_notify_attributes = NULL;
// 创建定时器
timer_create(CLOCK_REALTIME, &sev, timer);
// 设置定时器触发时间
its.it_value.tv_sec = sed;
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
// 启动定时器
timer_settime(*timer, 0, &its, NULL);
}
int main() {
// 打印当前实际按计时器的值
time_t currTime = time(NULL);
printf("当前实际时间:%s", ctime(&currTime));
start_timer(task, 5);
start_timer(task, 3);
start_timer(task, 10);
// 等待定时器触发
while (1) {
sleep(1);
}
return 0;
}
|