/*秒级定时器*/
void seconds_sleep(unsigned long seconds)
{
if(seconds == 0) return;
struct timeval tv;
tv.tv_sec=seconds;
tv.tv_usec=0;
int err;
do{
err=select(0,NULL,NULL,NULL,&tv);
}while(err<0 && errno==EINTR);
}
/*毫秒定时器*/
void milliseconds_sleep(unsigned long mSec)
{
if(mSec == 0) return;
struct timeval tv;
tv.tv_sec=mSec/1000;
tv.tv_usec=(mSec%1000)*1000;
int err;
do{
err=select(0,NULL,NULL,NULL,&tv);
}while(err<0 && errno==EINTR);
}
/*微秒定时器*/
void microseconds_sleep(unsigned long uSec)
{
if(uSec == 0) return;
struct timeval tv;
tv.tv_sec=uSec/1000000;
tv.tv_usec=uSec%1000000;
int err;
do{
err=select(0,NULL,NULL,NULL,&tv);
}while(err<0 && errno==EINTR);
}
int main()
{
int i;
for(i=0;i<5;++i){
printf("%d\n",i);
//seconds_sleep(2);
//milliseconds_sleep(2000);
microseconds_sleep(2000000);
}
}
本文介绍了一种使用select函数实现的定时器功能,涵盖了秒级、毫秒级和微秒级的定时需求。通过修改timeval结构体中的时间单位,可以灵活调整定时精度。
1631

被折叠的 条评论
为什么被折叠?



