linux下定时器的实现

简介:

  linux下经常有这样的需求,需要定时轮询执行某种任务,当然,用shell脚本的话,crontab和at就可以满足要求。如果从C语言的角度来看,实现定时器也是一个比较简单的任务,因为具有普遍性,做此记录,备忘。

原理剖析:

  定时器的主要任务是定时和轮询,如果对libc的api熟悉的话,很容易想到settitimer函数,这不是一个现成的定时器么,coder需要做的,仅仅是把设定时间和当前时间的差值计算代入即可。

代码:

  

 1 /*
 2  * =====================================================================================
 3  *
 4  *       Filename:  7.c
 5  *
 6  *    Description:  
 7  *
 8  *        Version:  1.0
 9  *        Created:  2015年05月21日 16时42分48秒
10  *       Revision:  none
11  *       Compiler:  gcc
12  *
13  *         Author:  3me (), 
14  *   Organization:  
15  *
16  * =====================================================================================
17  */
18 #include <stdlib.h>
19 
20 #include <sys/time.h>
21 #include <signal.h>
22 #include <time.h> 
23 #include <stdio.h>
24 #include <unistd.h>
25 
26 #define UPDATE_TIME 3
27 #define INTERVAL_TIME 24
28 
29 
30 void my_alarm_handler(int a){
31         printf("signal trigger.
");
32 }
33 
34 
35 int main(){
36 
37         long tv;
38         time_t timep; 
39         struct tm *p; 
40         time(&timep); 
41         p=localtime(&timep); 
42 
43         printf("%d:%d:%d
",  p->tm_hour, p->tm_min, p->tm_sec); 
44 
45         if ( p->tm_hour < UPDATE_TIME )
46         {
47                 tv = ((UPDATE_TIME - p->tm_hour - 1)* 60 + p->tm_min) * 60;
48         }
49         else 
50         {
51                 tv = ( (24 + UPDATE_TIME - p->tm_hour - 1) * 60 + p->tm_min) * 60;
52 
53         }
54 
55         struct itimerval t;
56         t.it_interval.tv_usec = 0;
57         t.it_interval.tv_sec = INTERVAL_TIME*60*60;
58         t.it_value.tv_usec = 0;
59         t.it_value.tv_sec = tv;
60 
61         if( setitimer( ITIMER_REAL, &t, NULL) < 0 ){
62                 perror("settime error.");
63                 return -1;
64         }
65         signal( SIGALRM, my_alarm_handler );
66 
67         while(1){
68 
69                 sleep(2);
70 
71         }
72 
73         return EXIT_SUCCESS;
74 }
原文地址:https://www.cnblogs.com/3me-linux/p/4535318.html