Libuv uv_timer_t 学习笔记

官方程序代码

#include 
#include 

uv_loop_t *loop;
uv_timer_t gc_req;
uv_timer_t fake_job_req;

void gc(uv_timer_t *handle) {
    fprintf(stderr, "Freeing unused objects\n");
}

void fake_job(uv_timer_t *handle) {
    fprintf(stdout, "Fake job done\n");
}

int main() {
    loop = uv_default_loop();                               // 定义并初始化一个默认的循环

    uv_timer_init(loop, &gc_req);                           // 初始化定时器 gc_req
    uv_unref((uv_handle_t*) &gc_req);                       // 如果没有其他任务,则释放 gc_req 定时任务

    uv_timer_start(&gc_req, gc, 0, 2000);                   // 启动 gc_req 定时器, 0 毫秒开始,每 2000 毫秒执行一次

    uv_timer_init(loop, &fake_job_req);                     // 初始化定时器 fake_job_req
    uv_timer_start(&fake_job_req, fake_job, 9000, 0);       // 启动 fake_job_req 定时器, 9000 毫秒后开始执行, 不需要循环执行
    
    uv_run(loop, UV_RUN_DEFAULT);                           // 运行 loop 循环
    
    return 0;
}

说明几个重要的地方

  1. uv_unref((uv_handle_t*) &gc_req);
    这个函数的意思是,如果除了定时器 gc_req, 如果当前没有其他任务的时候,则退出定时器 gc_req,当前这个例子中,如果不加这条指令,则这个程序会永无休止的运行下去,但是现在加了这条,因为 fake_job_req 这个定时只会在启动时执行一次,那么程序就会在 fake_job_req 执行完这一次后,就会释放 gc_req ,程序退出。
  2. int uv_timer_init(uv_loop_t* loop, uv_timer_t* handle)
    初始化 定时器句柄
  3. int uv_timer_start(uv_timer_t* handle, uv_timer_cb cb, uint64_t timeout, uint64_t repeat)
    这个函数应该称它为 设置定时器, 而不是启动定时器, 因为定时器运行是从 uv_run() 开始的。
    这个函数有 4 个参数:
    1. uv_timer_t *handle 定时器句柄,用于保存当前定时器的一个 id,后续可以通过这个 id, 重新配置、重启、关闭 定时器。
    2. uv_timer_cb cb 定时器回调函数指针,定时时间到的时候会调用这个函数,回调函数的格式必须是 void (*uv_timer_cb)(uv_timer_t *handle)
    3. uint64_t timeout 这个参数指的是,在 uv_run() 之后多久启动定时器,单位是毫秒。
    4. uint64_t repeat 这个参数是指定,定时器循环定时的时间,也就是重复调用的时间,单位是毫秒。
  4. 测试截图
    加了 uv_unref((uv_handle_t*) &gc_req); 时,程序运行结果,程序会在 fake_job_req 结束后退出(也就是空闲的时候会退出)。
    Libuv uv_timer_t 学习笔记_第1张图片
    取消uv_unref((uv_handle_t*) &gc_req); 时,程序运行结果,程序会一直运行下去。
    Libuv uv_timer_t 学习笔记_第2张图片

关于 uv_timer_t 其他几个函数

  1. int uv_timer_stop(uv_timer_t* handle)
    停止定时器,执行后就不再会调用定时器回调函数了。
  2. int uv_timer_again(uv_timer_t* handle)
    停止定时器后,如果你想从新启动定时器,调用这个函数就可以了。
  3. void uv_timer_set_repeat(uv_timer_t* handle, uint64_t repeat)
    动态设置定时器,循环调用延时时间。
    举个例子:
    如果当前定时的定时时间是 1000ms,如果此时调用 uv_timer_set_repeat(&t1, 100); 设置新的定时时间 100ms, 则定时器会在 100ms 调用回调函数,如果定时器在之前已经运行了 101ms, 则会立即执行,如果定时器之前运行了 50 ms ,则在 50ms 后会调用回调函数,同理将定时器增加到 10000ms uv_timer_set_repeat(&t1, 10000); 如果定时器之前已经运行了 999ms ,则需要在 9001 后才会调用回调函数。
  4. uint64_t uv_timer_get_repeat(const uv_timer_t* handle)
    获取定时器,循环调用时间。

你可能感兴趣的:(Libuv uv_timer_t 学习笔记)