summaryrefslogtreecommitdiff
path: root/src/myTimer.c
blob: 04abef0a872ebc93b580e86ad2c4e1a86b84e582 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

#include <time.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/time.h>
#include <signal.h>

#include "main.h"
#include "list.h"
#include "myTimer.h"

#ifndef BUBLIC_SERVER
#include "interface.h"
#endif

static list_t *listTime;

static bool_t isTimerInit = FALSE;

bool_t isMyTimerInicialized()
{
	return isTimerInit;
}

void initTimer()
{
	listTime = newList();
	isTimerInit = TRUE;
}

my_time_t getMyTime()
{
	static struct timeval start;
	struct timeval now;
	static char first = '0';
	my_time_t ticks;

	if(  first == '0' )
	{
		gettimeofday(&start, NULL);
		first = 'x';
	}

	gettimeofday(&now, NULL);

	ticks = (now.tv_sec-start.tv_sec)*1000+(now.tv_usec-start.tv_usec)/1000;

	return ticks;
}

int addTimer(void (*fce)(void *p), void *arg, my_time_t my_time)
{
	static int new_id = 0;
	my_timer_t *new;
	my_time_t currentTime;

 	currentTime = getMyTime();

	new = malloc( sizeof(my_timer_t) );
	assert( new != NULL );

	new->id = new_id++;
	new->fce = fce;
	new->arg = arg;
	new->time = currentTime + my_time;

	addList(listTime, new);

	return new->id;
}

void eventTimer()
{
	int i;
	my_timer_t *thisTimer;
	my_time_t currentTime;

 	currentTime = getMyTime();

	for( i = 0 ; i < listTime->count ; i++ )
	{
		thisTimer = (my_timer_t *)listTime->list[i];
		assert( thisTimer != NULL );

		if( currentTime >= thisTimer->time )
		{
			thisTimer->fce(thisTimer->arg);

			if( isTimerInit == FALSE )
			{
				return;
			}

			delListItem(listTime, i, free);
			i--;
		}
	}
}

void delTimer(int id)
{
	int i;
	my_timer_t *thisTimer;

	for( i = 0 ; i < listTime->count ; i++ )
	{
		thisTimer = (my_timer_t *)listTime->list[i];
		assert( thisTimer != NULL );

		if( thisTimer->id == id )
		{
			delListItem(listTime, i, free);
			return;
		}
	}

	assert( ! "Uloha s id nenajdena !" );
}

void delAllItemTimer()
{
	quitTimer();
	initTimer();
}

void quitTimer()
{
	destroyListItem(listTime, free);
	isTimerInit = FALSE;
}