07.libevent定时器使用

test.cpp

#include<iostream>
#include<event2/event.h>
#include <event2/event.h>
#include <event2/thread.h>
#include<event2/listener.h>
#ifndef _WIN32
#include <signal.h>
#else
#endif
using namespace std;

static timeval t1 = { 1,0 };

void timer1(int sock, short which, void* arg)
{
	event* ev = (event *)arg;
	cout << "[ timer1 ]" << endl;
	if (!evtimer_pending(ev, &t1))
	{
		evtimer_del(ev);
		evtimer_add(ev, &t1);
	}
}

void timer2(int sock, short which, void* arg)
{
	cout << "[ timer2 ]" << endl;
}



int main(int argc, char** argv)
{
#ifdef _WIN32 
	//初始化socket库
	WSADATA wsa;
	WSAStartup(MAKEWORD(2, 2), &wsa);
#else
	//忽略管道信号,发送数据给已关闭的socket
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
		return 1;
#endif

    event_base* base = event_base_new();

	//定时器
	cout << "timer ->" << endl;

	//定时器,非持久事件,只进入一次
	event* evl = evtimer_new(base, timer1, event_self_cbarg());
	if (!evl)
	{
		cout << "evtimer_new timer1 failed! " << endl;
		return -1;
	}
	
	evtimer_add(evl, &t1);

	static timeval t2;
	t2.tv_sec = 1;
	t2.tv_usec = 200000;//微秒

	event* ev2 = event_new(base, -1, EV_PERSIST, timer2, 0);
	event_add(ev2, &t2);

    //进入事件主循环
    event_base_dispatch(base);
    event_base_free(base);

    return 0;
}

linux下makefile

test:test.cpp
        g++ $^ -o $@ -levent
        ./$@
clean:
        rm -rf test
        rm -rf *.o
~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值