libuv 之定时器的使用

libuv 定时器使用,一个定时器配合着一个回调函数,简单方便,只管定时和时间到了的处理函数,libuv去到哪都是回调,精华所在。

使用的API,主要是uv_timer_start

uv_timer_start,参数有4个,分别是:timer定时器,回调函数,延时时间,重复间隔。

UV_EXTERN int uv_timer_start(uv_timer_t* handle, uv_timer_cb cb, uint64_t timeout, uint64_t repeat);

敲黑板,画重点:在调用完之后,或者需要主动关闭定时器释放时,不再使用的时候,一定要调用uv_close,不然会造成内存泄露!

代码如下:

#ifdef _WIN32 
#include <vld.h>
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"Iphlpapi.lib")
#pragma comment(lib,"Psapi.lib")
#endif

#include <stdio.h>
#include <iostream>
#include <uv.h>

using namespace std;

int repeat = 0;
static int repeatCount = 10;

static void callback(uv_timer_t *handle) {
	repeat = repeat + 1;
	if (repeatCount == repeat) {
		uv_timer_stop(handle);
		//用完一定要调用uv_close,不然会内存泄露
		uv_close((uv_handle_t*)handle, NULL);
	}
}


int main() {
	uv_loop_t *loop = uv_default_loop();

	uv_timer_t timer_req;

	uv_timer_init(loop, &timer_req);

	uv_timer_start(&timer_req, callback, 1000, repeatCount);

	return uv_run(loop, UV_RUN_DEFAULT);
}
发布了70 篇原创文章 · 获赞 48 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/fwb330198372/article/details/52842303