libuv::定时器

 

//初始化句柄。
int uv_timer_init(uv_loop_t * loop,uv_timer_t * handle)

//启动计时器。超时和重复的时间以毫秒为单位。
如果超时为零,则回调在下一个事件循环迭代时触发。如果repeat为非零值,则回调将在超时 毫秒后首先触发,然后在重复毫秒后重复触发。
int uv_timer_start(uv_timer_t *  handle,uv_timer_cb  cb,uint64_t  timeout,uint64_t  repeat )

//停止计时器,将不再调用该回调。
int uv_timer_stop(uv_timer_t *  handle )

//停止计时器,如果要重复,则使用重复值作为超时重启它。如果计时器从未启动过,则返回UV_EINVAL。
int uv_timer_again(uv_timer_t *  handle )

//获取计时器重复值。
uint64_t uv_timer_get_repeat( const uv_timer_t *  handle )

//获取计时器到期值;如果到期,则返回0。时间是相对于的 uv_now()。
uint64_t uv_timer_get_due_in( const uv_timer_t *  handle )

 

#include <cstdio>
#include <stdio.h>
#include <stdlib.h>
#include <libuv/uv.h>
#include <unistd.h>

void gc(uv_timer_t* handle) {
    printf("timer do something\n");
}

void fake_job(uv_timer_t* handle) {
    printf("do once\n");
}

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

    //初始化定时器
    uv_timer_t time_req;
    uv_timer_init(loop, &time_req);

    //如果没有其他任务,则释放 gc_req 定时任务
    //uv_unref((uv_handle_t*)&gc_req);

    //启动计时器。超时和重复的时间以毫秒为单位。
    uv_timer_start(&time_req, gc, 0, 5000);

    //初始化定时器 once_req
    uv_timer_t once_req;
    uv_timer_init(loop, &once_req);
    //启动 fake_job_req 定时器, 3000 毫秒后开始执行, 不需要循环执行
    uv_timer_start(&once_req, fake_job, 3000, 0);

    //运行 loop 循环
    return uv_run(loop, UV_RUN_DEFAULT);
}

 

posted @ 2020-12-06 15:45  osbreak  阅读(906)  评论(0编辑  收藏  举报