1498
|
1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
|
2
|
|
3 #include "timeout.h"
|
|
4
|
|
5 list *icq_TimeoutList = NULL;
|
|
6
|
|
7 void (*icq_SetTimeout)(long length);
|
|
8
|
|
9 int icq_TimeoutCompare(icq_Timeout *t1, icq_Timeout *t2)
|
|
10 {
|
|
11 return (t1->expire_time - t2->expire_time);
|
|
12 }
|
|
13
|
|
14 icq_Timeout *icq_TimeoutNew(int length, icq_TimeoutHandler handler,
|
|
15 void *data)
|
|
16 {
|
|
17 icq_Timeout *t = (icq_Timeout *)malloc(sizeof(icq_Timeout));
|
|
18
|
|
19 if (t)
|
|
20 {
|
|
21 int count = icq_TimeoutList->count;
|
|
22
|
|
23 t->length = length;
|
|
24 t->handler = handler;
|
|
25 t->data = data;
|
|
26 t->expire_time = time(NULL) + length;
|
|
27 t->single_shot = 1;
|
|
28
|
|
29 list_insert_sorted(icq_TimeoutList, t);
|
|
30
|
|
31 if (count == 0)
|
|
32 icq_TimeoutDoNotify();
|
|
33 }
|
|
34
|
|
35 return t;
|
|
36 }
|
|
37
|
|
38 void icq_TimeoutDelete(icq_Timeout *timeout)
|
|
39 {
|
|
40 list_remove(icq_TimeoutList, timeout);
|
|
41 free(timeout);
|
|
42 }
|
|
43
|
|
44 int _icq_HandleTimeout(void *p, va_list data)
|
|
45 {
|
|
46 icq_Timeout *t = p;
|
|
47 time_t current_time = va_arg(data, time_t);
|
|
48 int complete = 0;
|
|
49
|
|
50 if (t->expire_time <= current_time)
|
|
51 (*t->handler)(t->data);
|
|
52 else
|
|
53 /* traversal is complete when we reach an expire time in the future */
|
|
54 complete = 1;
|
|
55
|
|
56 if (t->single_shot)
|
|
57 icq_TimeoutDelete(t);
|
|
58 else
|
|
59 t->expire_time = current_time + t->length;
|
|
60
|
|
61 return complete;
|
|
62 }
|
|
63
|
|
64 void icq_HandleTimeout()
|
|
65 {
|
|
66 time_t current_time = time(NULL);
|
|
67
|
|
68 /* call handler functions for all timeouts that have expired */
|
|
69 list_traverse(icq_TimeoutList, _icq_HandleTimeout, current_time);
|
|
70
|
|
71 if (icq_TimeoutList->count)
|
|
72 icq_TimeoutDoNotify();
|
|
73 }
|
|
74
|
|
75 void icq_TimeoutDoNotify()
|
|
76 {
|
|
77 time_t current_time = time(NULL);
|
|
78
|
|
79 icq_Timeout *t = (icq_Timeout *)list_first(icq_TimeoutList);
|
|
80 long length = t->expire_time - current_time;
|
|
81 if (icq_SetTimeout)
|
|
82 (*icq_SetTimeout)(length);
|
|
83 }
|