添加定时器的动作非常的简单,本质只是一个链表的插入而已:
清单 6. 向定时器链表中添加定时器
/**
* Add a timer to timer list.
*
* @param interval The timer interval(second).
* @param cb When cb!= NULL and timer expiry, call it.
* @param user_data Callback's param.
* @param len The length of the user_data.
*
* @return The timer ID, if == INVALID_TIMER_ID, add timer fail.
*/
timer_id add_timer(int interval, timer_expiry *cb, void *user_data, int len)
{
struct timer *node = NULL;
if (cb == NULL || interval <= 0) {
return INVALID_TIMER_ID;
}
if(timer_list.num < timer_list.max_num) {
timer_list.num++;
} else {
return INVALID_TIMER_ID;
}
if((node = malloc(sizeof(struct timer))) == NULL) {
return INVALID_TIMER_ID;
}
if(user_data != NULL || len != 0) {
node->user_data = malloc(len);
memcpy(node->user_data, user_data, len);
node->len = len;
}
node->cb = cb;
node->interval = interval;
node->elapse = 0;
node->id = timer_list.num;
LIST_INSERT_HEAD(&timer_list.header, node, entries);
return node->id;
}