# MultiTimer
## 简介
MultiTimer 是一个软件定时器扩展模块,可无限扩展你所需的定时器任务,取代传统的标志位判断方式, 更优雅更便捷地管理程序的时间触发时序。
## 使用方法
1. 配置系统时间基准接口,安装定时器驱动;
```c
uint64_t platform_ticks_get_interface(void) {
/* Platform implementation */
}
multi_timer_install_ticks(platform_ticks_get_interface);
```
2. 实例化一个定时器对象;
```c
multi_timer_t g_timer1_;
```
3. 设置定时时间,超时回调处理函数, 用户上下指针,启动定时器;
```c
int multi_timer_start(&g_timer1_, uint64_t timing, multi_timer_callback_t callback, void* user_data);
```
4. 在主循环调用定时器后台处理函数
```c
int main(int argc, char *argv[])
{
...
while (1) {
...
multi_timer_yield();
}
}
```
## 功能限制
1.定时器的时钟频率直接影响定时器的精确度,尽可能采用1ms/5ms/10ms这几个精度较高的tick;
2.定时器的回调函数内不应执行耗时操作,否则可能因占用过长的时间,导致其他定时器无法正常超时;
3.由于定时器的回调函数是在 multi_timer_yield 内执行的,需要注意栈空间的使用不能过大,否则可能会导致栈溢出。
## Examples
见example目录下的测试代码 test_linux.c为linux平台的测试demo。
```c
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include "../multi_timer.h"
// global variable
multi_timer_t g_timer1_;
multi_timer_t g_timer2_;
multi_timer_t g_timer3_;
uint64_t platform_ticks_get_interface(void) {
struct timespec current_time;
clock_gettime(CLOCK_MONOTONIC, ¤t_time);
return (uint64_t)((current_time.tv_sec * 1000) + (current_time.tv_nsec / 1000000)); // unit is millisecond.
}
void example_timer1_callback(multi_timer_t* timer, void *user_data) {
printf("[%012ld] Timer:%p callback-> %s.\r\n", platform_ticks_get_interface(), timer, (char*)user_data);
multi_timer_start(timer, 1000, example_timer1_callback, user_data);
}
void example_timer2_callback(multi_timer_t* timer, void *user_data) {
printf("[%012ld] Timer:%p callback-> %s.\r\n", platform_ticks_get_interface(), timer, (char*)user_data);
}
void example_timer3_callback(multi_timer_t* timer, void *user_data) {
printf("[%012ld] Timer:%p callback-> %s.\r\n", platform_ticks_get_interface(), timer, (char*)user_data);
multi_timer_start(timer, 4567, example_timer3_callback, user_data);
}
int main(int argc, char *argv[]) {
multi_timer_install_ticks(platform_ticks_get_interface);
multi_timer_start(&g_timer1_, 1000, example_timer1_callback, "1000ms CYCLE timer");
multi_timer_start(&g_timer2_, 5000, example_timer2_callback, "5000ms ONCE timer");
multi_timer_start(&g_timer3_, 3456, example_timer3_callback, "3456ms delay start, 4567ms CYCLE timer");
while (1) {
multi_timer_yield();
}
}
```