定时方法

1.定时机制:
定时是在一段时间之后触发某段代码的机制,我们可以在这段代码中依次处理所有到期的定时器。

有三种定时方法:
①socket选项SO_RVETIMEO和S0_SEDTIMEO
②SIGALRM信号
③I/O复用系统调用的超时参数

先说第一个
1. socket选项SO_RVETIMEO和S0_SEDTIMEO

它们分别用来设置接受数据和发送数据的超时时间。
所以它们仅对相关专用的系统调用有用,send,sendmsg,recv,recvmsg,accept,connect(错误返回-1,设置error为EINPROGRESS)。
可以根据它们的返回值以及error来确定超时时间是否已到,进而决定是否处理定时任务。

以代码为列

#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#incldue<stdlib.h>
#include<assert.h>
#include<stdio.h>
#include<errno.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>

int timeout_connect(const char* ip,int port
,int time)
{
    int ret = 0;
    struct sockaddr_in address;
    bzero(&address,sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(AF_INET,ip,&address.sin_addr);
    address.sin_port = htons(port);

    int sockfd = socket(PF_INET,SOCK_STREAM,0);
    assert(sockfd >= 0);

    struct timeval timeout;
    timeout.tv_sec = time;
    timeout.tv.usec = 0;
    socklen_t len = sizeof(timeout);
    ret = setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,&timeout,len);
    assert(ret != -1);

    ret = connect(sockfd,(struct sockaddr*)&address,sizeof(address));
    if(ret == -1)
    {
超时对应的错误EINPROGRESS,
        if(errno == EINPROGRESS)
        {
            printf("connecting timeout,
            process timeout logic\n");
            return -1;
        }
        printf("error occur when connecting 
        to server\n");
        return -1;
    }
    return sockfd;
}

int main(int argc,char* argv[])
{
    if(argc <= 2)
    {

    }
    const char * ip = argv[1];
    int port = atoi(argv[2]);

    int sockfd = timeout_connect(ip,port,10);
    if(sockfd < 0)
    {
        return 1;
    }
    return 0;
}
  1. SIGALRM信号:由alarm和setitimer函数设置的实时闹钟一旦超时,就会触发SIGALRM信号,要处理多个定时任务,就要不断的触发此信号。信号按照固定的频率生成,定时周期T
基于升序链表的定时器

两个成员:1.超时时间,2.任务回调函数
链表作为容器串联所有的定时器,还要包含指向
下一个定时器的指针。
#ifndef LST_TIMER
#define LST_TIMER

#include<time.h>
#define BUFFER_SIZE 64
class util_timer;

struct client_data
{
    sockaddr_in address;
    int sockfd;
    char buf[BUFFER_SIZE];读缓存
    util_timer* timer;定时器
};

class util_timer
{
public:
    util_timer():prev(NULL),next(NULL){}
public:
    time_t expire; 任务的超时时间
    void (*cb_func)(client_data*);任务回调函数
回调函数处理的客户数据,由定时器的执行者传递给回调函数
    client_data* user_data;
    util_timer* prev;
    util_timer* next;
};

class sort_timer_lst
{
public:
    sort_timer_lst():head(NULL),tail(NULL){}
    ~sort_timer_lst()
    {
        util_timer* tmp = head;
        while(tmp)
        {
            head = tmp->next;
            delete tmp;
            tmp = head;
        }
    }
    将目标定时器添加到链表
    void add_timer(util_timer* timer)
    {
        if(!timer)
        {
            return ;
        }
        if(!head)
        {
            head = tail = timer;
            return ;
        }
        if(timer->expire < head->expire)
        {
            timer->next = head;
            head->prve = timer;
            head = timer;
            return ;
        }
        add_timer(timer,head);
    }

    当某个定时任务发生变化,调整位置
    void adjust_timer(util_timer* timer)
    {
        if(!timer)
            return;
        util_timer* tmp = timer->next;
        if(!tmp || (timer->expire < tmp->expire))
        {
            return;
        }
        if(timer == head)
        {
            hread = head->next;
            head->prve = NULL;
            timer->next = NULL;
            add_timer(timer,head);
        }
        else
        {
            timer->prve->next = timer->next;
            time->next->prve = timer->prve;
            add_timer(timer,timer->next);
        }
    }
    void del_timer(util_timer* timer)
    {
        if(!timer)
        {
            return;
        }
        if((timer == head)&&(timer == tail))
        {
            delete timer;
            head = NULL;
            tail = NULL;
            return ;
        }
        if(timer == head)
        {
            head = head->next;
            head->prve = NULL;
            delete tmer;
            return;
        }
        if(timer == tail)
        {
            tail = tail->prve;
            tail->next = NULL;
            delete timer;
            return;
        }
        timer->prve->next = timer->next;
        timer->next->prve = timer->prve;
        delete timer;
    }

SIGALRM每次触发就在其信号处理函数中执行一次
tick函数,以处理链表上到期任务
    void tick()
    {
        if(!head)
            return;
        printf("timer tick\n");
        time_t cur = time(NULL);获得系统当前时间
        util_timer* tmp = head;
    从头结点开始处理每个定时器,直到遇到一个尚未到期的
    这是核心逻辑
        while(tmp)
        {
    每个定时器都用绝对时间,可以和当亲时间比较是否到期
            if(cur < tmp->expire)
                break;
            调用回调函数,执行定时任务
            tmp->cb_func(tmp->user_data);
            执行完就删除
            并且重置当前的头结点
            head = tmp->next;
            if(head)
            {
                head->prve = NULL;
            }
            delete tmp;
            tmp = head;
        }
    }
private:
    void add_timer(util_timer* timer,util_timer* las_head
    )
    {
    该函数表示将timer添加到lst_head之后的部分区
        util_timer*prve = lst_head;
        util_timer* tmp = prve->next;

        while(tmp)
        {
            if(timer->expire < tmp->expire)
            {
                prve->next = timer;
                timer->next = tmp;
                tmp->prve = timer;
                timer->prve = prve;
                break;
            }
            prve = tmp;
            tmp = tmp->next;
        }
        if(!tmp)
        {
            prve->next = timer;
            timer->prve = prve;
            timer->next = NULL;
            tail = timer;
        }
    }
private:
    util_timer* head;
    util_timer* tail;
};
#endif
  1. I/O复用系统调用的超时参数

linux下的3组I/O复用系统调用都带有超时参数,因此他们不仅能统一处理信号和I/O事件,也能统一处理定时事件,但是由于I.O复用系统可能在超时时间到期之前就返回(有I/O事件发生),就需要不断更新定时参数以反映剩余的时间

#define TIMEOUT 5000

int timeout = TIMEOUT;
time_t start = time(NULL);
time_t end = time(NULL);
while(1)
{
    printf("the timeout is now %d mil-seconds\n",timeout);
    start = time(NULL);
    int number = epoll_wait(epollfd,events,MAX_EVENT_NUMBER,timeout);
    if((number < 0)&&(errno != EINTR)
    {
        printf("epoll failure\n");
        break;
    }
    if(number == 0)
    {
        timeout = TIMEOUT;
        continue;
    }
    end = time(NULL);
若返回值大于0,则本次epoll_wait的调用持续时间是end-start
我们要将定时时间timeout减去这段时间,以获得下次的超时参数
    timeout -= (end - start)* 1000;
重新计算的tiomeout可能等于0 ,说明本次调用返回时,
不仅有文件描述符就绪,而且超时时间刚好到达。处理定时任务
    if(timeout < = 0)
    {
        timeout  = TIMEOUT;

    }
}

6.高性能定时器
1.时间轮

使用哈希表的思想,将定时器散列到不同的链表上,这样每条链表上的定时器数目都将明显少于原来的排序链表上的定时器数目、

一个简单的时间lun
#ifndef TIME_WHEEL_TIMER
#define TIME_WHEEL_TIMER

#include<time.h>
#include<netinet/in.h>
#include<stdio.h>

#define BUFFER_SIZE 64
class tw_timer;
绑定socket和定时器
struct client_data
{
    sockaddr_in address;
    int sockfd;
    char buf[BUFFER_SIZE];
    tw_timer * timer;
};
class tw_timer
{
public:
    tw_timer(int rot,int ts):next(NULL),prve(NULL),rotation(rot),
    time_slot(ts){}
public:
    int rotation;记录定时器在时间轮转多少圈后生效
    int time_slot;定时器属于时间轮上那个槽
    void (*cb_func)(client_data*);
    定时器回调函数
    client_data* user_data;客户数据
    tw_timer*next;
    tw_timer* prve;
};

class time_wheel
{
public:
    time_wheel():cur_slot(0)
    {
        for(int i = 0;i < N;++i)
        {
            slots[i] = NULL;初始化每个槽的头结点
        }
    }
    ~time_wheel()
    {
        for(int i = 0;i < N;++i)
        {
            tw_timer* tmp = slots[i];
            while(tmp)
            {
                slots[i] = tmp->next;
                delete tmp;
                tmp = slots[i];
            }
        }
    }
    tw_timer* add_timer(int timeout)
    {
        if(timeout < 0)
        {
            return NULL;
        }
根据带插入的定时器超时值计算它在时间轮转动多少个
滴答后被触发,如果带插入定时器的超时值小于间隔SI,
则将滴答向上折合为1,否则向下折合为timeout/SI;
        if(timeout < SI)
        {
            ticks = 1;
        }
        else
        {
            ticks = timeout /SI;
        }
        int rotation = ticks/N;
        int ts= (cur_slot +(ticks%N))&N;
        tw_timer* timer = new tw_timer(rotation,ts);

        (if!slots[ts])
        {
            printf(“add timer);
            slots[ts]= timer;
        }
        else
        {
            timer->next = slots[ts];
            slots[ts]->orve = timer;
            slots[ts] = timer;
        }
        return tiemr;
    }
    void del_timer(tw_timer* timer)
    {
        if(!timer)
        {
            return;
        }
        int ts = timer->time_slot;
        if(timer == slots[ts])
        {
            slots[ts] = slots[ts]->next;
            if(slots[ts])
            {
                slots[ts]->prve = NULL;            }
            delete timer;
        }
        else
        {
            timer->prve->next = timer->nexta;
            if(timer->next)
            {
                timer->next->prve = timer->prve;
            }
            delete timer;
        }
    }

    SI时间后,调用该函数,时间轮向前滚动一个槽的间隔
    void tick()
    {
        tw_timer* tmp = slots[cur_slot];
        取得时间轮上当前槽的头结点
        printf("cuurent slot is %d,"cur_slot);
        while(tmp)
        {
            printf("tick the timer once");
            如果当前ration值大于0,不生效
            if(tmp->rotation > 0)
            {
                tmp->rotaion--;
                tmp = tmp->next;
            }
            else
            {
                tmp->cb_func(tmp->user_data);

            }
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值