LINUX定时器--使用

封装一下定时器。

timer.h

#ifndef TIMER_H
#define TIMER_H

#define TIMER_INVALID_TIMER_ID (~0UL)
#ifndef ULONG
#define ULONG unsigned long
#endif
#ifndef VOID
#define VOID void
#endif

typedef VOID(*TIMER_FUNC_PF)(VOID*);
typedef enum 
{
    TIMER_LOOP = 0,
	TIMER_NO_LOOP,
}TIMER_MODE_E;
extern ULONG TimerCreate(TIMER_MODE_E enMode,
                         TIMER_FUNC_PF func,
				         VOID *pPara,
				         ULONG ulmSecond);
extern VOID TimerDestory(ULONG ulTimerId);
#endif

timer.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include "timer.h"



ULONG TimerCreate(TIMER_MODE_E enMode, TIMER_FUNC_PF func, VOID *pPara, ULONG ulmSecond)
{
    ULONG ulTimerId = TIMER_INVALID_TIMER_ID;
	int iRet = 0;
	struct sigevent ev;
	struct itimerspec tev;
	if (NULL == func || NULL == pPara)
	{
	    return ulTimerId;
	}
	memset(&ev, 0, sizeof(struct sigevent));
	ev.sigev_notify = SIGEV_THREAD;
	ev.sigev_signo = SIGALRM;
	ev.sigev_value.sival_ptr = pPara;
	ev.sigev_notify_function = (void(*)(sigval_t))func;
	
	iRet = timer_create(CLOCK_REALTIME, &ev, (timer_t*)&ulTimerId);
	if (0 == iRet)
	{
	    memset(&tev, 0, sizeof(struct itimerspec));
		tev.it_value.tv_sec = ulmSecond / 1000;
	    tev.it_value.tv_nsec = (ulmSecond % 1000) * 1000 * 1000;
		if (TIMER_LOOP == enMode)
		{
		    tev.it_interval = tev.it_value;
		}
		iRet = timer_settime((timer_t)ulTimerId, TIMER_ABSTIME, &tev, NULL);
		if (0 != iRet)
		{
		    TimerDestory(ulTimerId);
			ulTimerId = TIMER_INVALID_TIMER_ID;
		}
	}
    return ulTimerId;
}

VOID TimerDestory(ULONG ulTimerId)
{
    if (TIMER_INVALID_TIMER_ID != ulTimerId)
	{
	    timer_delete((timer_t)ulTimerId);
	}
	return;
}

测试(进度条):

main.c

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include "timer.h"
void probar( VOID * pRate)  
{  
    char buf[101];
    int rate = (*(int*)pRate)%101;
    const char *sta="-\\|/";
	memset(buf, '=',sizeof(buf));
	buf[100] = '\0';
    printf("[%-100s],%3d%%,[%c]\r",buf + 100 - rate,rate,sta[rate%4]);
	fflush(stdout);
	(*(int*)pRate) = rate + 1;
	return;
}  
int main ()
{
    int num= 0;
	ULONG ulTimerId = TIMER_INVALID_TIMER_ID;
    ulTimerId = TimerCreate(TIMER_LOOP,probar,(VOID*)&num,100);
	getchar();
	TimerDestory(ulTimerId);
    return 0;
}



编译:要指定 -lrt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值