#ifdef __cplusplusextern "C"{#endif#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h> // -lpthread#include "mt_timer.h"#ifdef __cplusplus}#endifTIMER_CREATE(timer_for_test);static int timer_task_id = -1;void release_task_handle(void *arg){char *data = (char*) arg;printf("[%ld]:release1 with data %s\n", time(NULL), data);}void task_timeout_handle(void *arg){char *data = (char*) arg;printf("[%ld]:timeout1 with data %s\n", time(NULL), data);}void timeout_handle_2(void *arg){printf("[%ld]:timeout2\n", time(NULL));}int mt_timer_start(void){struct itimerspec itimespec;// 在超时事件发生以后,还会重复多少次,无限次为-1int repeat_cnt = 2;// 最大定时任务数量int max_timer_cnt = 5;// 定时器参数char data[2] = {"a"};// 初始化定时器,限制最大定时任务的数量TIMER_INIT(timer_for_test, max_timer_cnt);// 清空定时器(如果不是第一次运行这个函数,就把之前的任务清空)if(timer_task_id != -1){TIMER_DEL(timer_for_test, timer_task_id);timer_task_id = -1;}/******************* 超时参数:**********************/// 单次超时时间// it_value即是超时时间(相对时间)itimespec.it_value.tv_sec = 2;itimespec.it_value.tv_nsec = 0;// 在单次超时以后,所开始的周期定时事件// 若想定义周期定时任务,则设置it_interval成员;// 若不想定义周期定时任务,则需设置it_interval成员都为0。if(repeat_cnt == 0){itimespec.it_interval.tv_sec = 0;itimespec.it_interval.tv_nsec = 0;}else{itimespec.it_interval.tv_sec = itimespec.it_value.tv_sec + 1;itimespec.it_interval.tv_nsec = itimespec.it_value.tv_nsec + 1;}// 添加一个定时任务timer_task_id = TIMER_ADD(timer_for_test, &itimespec, // 设置定时器和超时参数repeat_cnt, // 重复次数task_timeout_handle, data, // 定时任务超时后执行的动作,+ 执行时所需的自定义数据release_task_handle); // 定时任务被TIMER_DEL或者TIMER_CLEAR删除以后执行的动作(可为空),参数也是用自定义数据//TIMER_ADD(timer_for_test, &itimespec, repeat_cnt, task_timeout_handle, NULL, NULL);printf("[%ld]:timer_add : %d\n", time(NULL), TIMER_COUNT(timer_for_test));return 0;}int mt_timer_stop(void){// 删除指定定时任务TIMER_DEL(timer_for_test, timer_task_id);timer_task_id = -1;// 删除所有定时任务TIMER_CLEAR(timer_for_test);// 停止定时器TIMER_DEINIT(timer_for_test);}#if 1int test_mt_timer(void)//int main(void){mt_timer_start();while(1){getchar();TIMER_CLEAR(timer_for_test);//TIMER_DEL(timer_for_test, timer_task_id);break;}mt_timer_stop();}#endif
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。