Double Timer in C

Sometimes, you need a timer function. For example, you wanna check some live status every 5 seconds. By using sleep() is just not the way of doing, because the programs suppose to process for other things within this 5 seconds. We need a non-blocking timer function for that.

I created two functions uses timeval structure, and gettimeofday(), does the job of timer. Bellow is the code that illustrate how it works:
01 #include
02 #include
03
04 int SetTimer(struct timeval &tv, time_t sec)
05 {
06 gettimeofday(&tv,NULL);
07 tv.tv_sec+=sec;
08
09 return 1;
10 }
11
12 int CheckTimer(struct timeval &tv, time_t sec)
13 {
14 struct timeval ctv;
15 gettimeofday(&ctv,NULL);
16
17 if( (ctv.tv_sec > tv.tv_sec) )
18 {
19 gettimeofday(&tv,NULL);
20 tv.tv_sec+=sec;
21 return 1;
22 }
23 else
24 return 0;
25 }
26
27 int main()
28 {
29 struct timeval tv;
30 SetTimer(tv,5); //set up a delay timer
31 printf("start counting.\n");
32 while(1)
33 if (CheckTimer(tv,5)==1)
34 printf("Welcome to cc.byexamples.com\n");
35 return 0;
36 }

SetTimer() are use to set timer for the first time, and CheckTimer() use to check for the previous timer value. If it is times up, it will returns 1 at the same time initiate a new time value based on what you pass in at second argument. By doing that, is to allow flexibility of changing time interval value.

The minimum value for this timer is one second, for timer that works for less than one seconds, replace the SetTimer and CheckTimer as bellow:
01 int SetTimer(struct timeval &tv, int usec)
02 {
03 gettimeofday(&tv,NULL);
04 tv.tv_usec+=usec;
05
06 return 1;
07 }
08
09 int CheckTimer(struct timeval &tv, int usec)
10 {
11 struct timeval ctv;
12 gettimeofday(&ctv,NULL);
13
14 if( (ctv.tv_usec >= tv.tv_usec) || (ctv.tv_sec > tv.tv_sec) )
15 {
16 gettimeofday(&tv,NULL);
17 tv.tv_usec+=usec;
18 return 1;
19 }
20 else
21 return 0;
22 }

P.S. The code must be compile in c++, I uses reference which it is not available in c. You can compile the code with g++ ,

g++ -o mytimer{,.cc}

More examples of gcc/g++ compiler shows here.

Feel free to enhance it, I appreciate any comments regarding modifications, suggestions on how to improve it.

Share this

Related Posts

Previous
Next Post »