Linux定时器的使用

来源:互联网 发布:k30平板荷载试验算法 编辑:程序博客网 时间:2024/05/21 09:48

     使用定时器的目的无非是为了周期性的执行某一任务,或者是到了一个指定时间去执行某一个任务。要达到这一目的,一般有两个常见的比较有效的方法。一个是用linux内部 的三个定时器,另一个是用sleep, usleep函数让进程睡眠一段时间,使用alarm定时发出一个信号,还有那就是用gettimeofday, difftime等自己来计算时间间隔,然后时间到了就执行某一任务,但是这种方法效率低,所以不常用。

alarm

alarm用在不需要精确定时的时候,返回之前剩余的秒数。

NAME
       alarm - set an alarm clock for delivery of a signal
SYNOPSIS
       #include <unistd.h>
       unsigned int alarm(unsigned int seconds);
DESCRIPTION
       alarm  arranges  for a SIGALRM signal to be delivered to the process in
       seconds seconds.
       If seconds is zero, no new alarm is scheduled.
       In any event any previously set alarm is cancelled.

//cat timer.c#include <stdio.h>#include <unistd.h>#include <sys/time.h>#include <signal.h>  void func(){    printf("2 s reached.\n");}  int main(){   signal(SIGALRM,func);   alarm(2);   while(1);   return 0;}


Linux内置的3个定时器

Linux为每个任务安排了3个内部定时器:

ITIMER_REAL:实时定时器,不管进程在何种模式下运行(甚至在进程被挂起时),它总在计数。定时到达,向进程发送SIGALRM信号。

ITIMER_VIRTUAL:这个不是实时定时器,当进程在用户模式(即程序执行时)计算进程执行的时间。定时到达后向该进程发送SIGVTALRM信号。 

ITIMER_PROF:进程在用户模式(即程序执行时)和核心模式(即进程调度用时)均计数。定时到达产生SIGPROF信号。ITIMER_PROF记录的时间比ITIMER_VIRTUAL多了进程调度所花的时间。

定时器在初始化是,被赋予一个初始值,随时间递减,递减至0后发出信号,同时恢复初始值。在任务中,我们可以一种或者全部三种定时器,但同一时刻同一类型的定时器只能使用一个。

 

用到的函数有:

#include <sys/time.h>int getitimer(int which, struct itimerval *value);int setitimer(int which, struct itimerval*newvalue, struct itimerval* oldvalue);strcut timeval{     long tv_sec; /*秒*/     long tv_usec; /*微秒*/};struct itimerval{    struct timeval it_interval; /*时间间隔*/    struct timeval it_value;   /*当前时间计数*/};


it_interval用来指定每隔多长时间执行任务, it_value用来保存当前时间离执行任务还有多长时间。比如说, 你指定it_interval为2秒(微秒为0),开始的时候我们把it_value的时间也设定为2秒(微秒为0),当过了一秒, it_value就减少一个为1, 再过1秒,则it_value又减少1,变为0,这个时候发出信号(告诉用户时间到了,可以执行任务了),并且系统自动把it_value的时间重置为it_interval的值,即2秒,再重新计数。

为了帮助你理解这个问题,我们来看一个例子:

#include <stdio.h>#include <signal.h>#include <sys/time.h> int limit = 10;/* signal process */void timeout_info(int signo){    if(limit == 0)    {        printf("Sorry, time limit reached.\n");        return;    }    printf("only %d senconds left.\n", limit--);} /* init sigaction */void init_sigaction(void){    struct sigaction act;     act.sa_handler = timeout_info;    act.sa_flags   = 0;    sigemptyset(&act.sa_mask);    sigaction(SIGPROF, &act, NULL);} /* init */void init_time(void){    struct itimerval val;     val.it_value.tv_sec = 1;    val.it_value.tv_usec = 0;    val.it_interval = val.it_value;    setitimer(ITIMER_PROF, &val, NULL);}  int main(void){    init_sigaction();    init_time();    printf("You have only 10 seconds for thinking.\n");     while(1);    return 0;} 

对于ITIMER_VIRTUAL和ITIMER_PROF的使用方法类似,当你在setitimer里面设置的定时器为ITIMER_VIRTUAL的时候,你把sigaction里面的SIGALRM改为SIGVTALARM, 同理,ITIMER_PROF对应SIGPROF。

不过,你可能会注意到,当你用ITIMER_VIRTUAL和ITIMER_PROF的时候,你拿一个秒表,你会发现程序输出字符串的时间间隔会不止2秒,甚至5-6秒才会输出一个,至于为什么,自己好好琢磨一下^_^

sleep

下面我们来看看用sleep以及usleep怎么实现定时执行任务。

#include <signal.h>#include <unistd.h>#include <string.h>#include <stdio.h>static char msg[] = "I received a msg.\n";int len;void show_msg(int signo){    write(STDERR_FILENO, msg, len);}int main(){    struct sigaction act;        union sigval tsval;    act.sa_handler = show_msg;    act.sa_flags = 0;    sigemptyset(&act.sa_mask);    sigaction(50, &act, NULL);    len = strlen(msg);    while ( 1 )    {       sleep(2); /*睡眠2秒*/       /*向主进程发送信号,实际上是自己给自己发信号*/       sigqueue(getpid(), 50, tsval);    }    return 0;}

看到了吧,这个要比上面的简单多了,而且你用秒表测一下,时间很准,指定2秒到了就给你输出一个字符串。所以,如果你只做一般的定时,到了时间去执行一个任务,这种方法是最简单的。

时间差

下面我们来看看,通过自己计算时间差的方法来定时:

#include <signal.h>#include <unistd.h>#include <string.h>#include <stdio.h>#include <time.h>static char msg[] = "I received a msg.\n";int len;static time_t lasttime;void show_msg(int signo){      write(STDERR_FILENO, msg, len);}int main(){    struct sigaction act;    union sigval tsval;    act.sa_handler = show_msg;    act.sa_flags = 0;    sigemptyset(&act.sa_mask);    sigaction(50, &act, NULL);    len = strlen(msg);    time(&lasttime);    while ( 1 )    {        time_t nowtime;        /*获取当前时间*/        time(&nowtime);       /*和上一次的时间做比较,如果大于等于2秒,则立刻发送信号*/       if (nowtime - lasttime >= 2)       {           /*向主进程发送信号,实际上是自己给自己发信号*/           sigqueue(getpid(), 50, tsval);           lasttime = nowtime;       }     }     return 0;}

这个和上面不同之处在于,是自己手工计算时间差的,如果你想更精确的计算时间差,你可以把 time 函数换成gettimeofday,这个可以精确到微妙。

上面介绍的几种定时方法各有千秋,在计时效率上、方法上和时间的精确度上也各有不同,采用哪种方法,就看你程序的需要。



原创粉丝点击