Linux timer usage

Source: Internet
Author: User
Tags usleep
Linux timer use Postedon2010-03-2017: 40feisky read (1073) Comments (0) edit favorite use timer is nothing more than to periodically execute a task, or it takes a specified time to execute a task. To achieve this goal, there are generally...

 

Linux timer usage

Posted on feisky reading (1073) Comments (0) edit favorites

The purpose of using a timer is nothing more than to periodically execute a task, or to execute a task at a specified time. To achieve this goal, there are generally two common effective methods. One is to use three timers in linux, and the other is to use sleep. the usleep function allows the process to sleep for a period of time, and uses alarm to regularly send a signal. gettimeofday is also used, difftime and so on to calculate the time interval, and then execute a task when the time is reached, but this method is inefficient, so it is not commonly used.

Alarm

When no definite time is required, alarm returns the remaining seconds.

NAME

Alarm-set an alarm clock for delivery of a signal

SYNOPSIS

# Include

Unsigned int alarm (unsigned int seconds );

DESCRIPTION

Alarm arranges for a SIGALRM signal to be delivered to the process in

Seconds.

If seconds is zero, no new alarm is scheduled.

In any event any previusly set alarm is canceled.

Test procedure:

1 cat timer. c

2 # include

3 # include

4 # include

5 # include

6

7 void func ()

8 {

9 printf ("2 s reached. \ n ");

10}

11

12 int main ()

13 {

14 signal (SIGALRM, func );

15 alarm (2 );

16 while (1 );

17 return 0;

18}

19

Three built-in Linux timers

In Linux, three internal timers are arranged for each task:

ITIMER_REAL: a real-time timer, regardless of the mode in which the process runs (even when the process is suspended), it is always counting. Timed arrival: Sends a SIGALRM signal to the process.

ITIMER_VIRTUAL: this is not a real-time timer. when a process is in user mode (that is, when the program is executed), it calculates the execution time of the process. Send the SIGVTALRM signal to the process after the scheduled arrival.

ITIMER_PROF: processes are counted in user mode (during program execution) and Core mode (during process scheduling. Periodically generates a SIGPROF signal. ITIMER_PROF records more time than ITIMER_VIRTUAL.

During initialization, the timer is assigned an initial value, which is decreased with time. after decreasing to 0, the timer sends a signal and restores the initial value. In a task, one or all three timers can be used, but only one timer of the same type can be used at the same time.

 

The functions used include:

# Include

Int getitimer (int which, struct itimerval * value );

Int setitimer (int which, struct itimerval * newvalue, struct itimerval * oldvalue );

Strcut timeval

{

Long TV _sec;/* seconds */

Long TV _usec;/* microseconds */

};

Struct itimerval

{

Struct timeval it_interval;/* interval */

Struct timeval it_value;/* Current Time count */

};

It_interval is used to specify the time at which the task is executed, and it_value is used to save the time before the task is executed. For example, if you set it_interval to 2 seconds (microsecond to 0), we set the it_value time to 2 seconds (microsecond to 0) at the beginning, it_value is reduced to 1. After 1 second, it_value is reduced by 1 and becomes 0. at this time, a signal is sent (indicating that the task can be executed when the time is reached ), in addition, the system automatically resets the it_value time to the it_interval value, that is, 2 seconds, and then recalculates the value.

To help you understand this problem, let's look at an example:

1 # include

2 # include

3 # include

4

5 /*

6 *************************************** **************************************** ************************

7 ** Function name: main ()

8 ** Descriptions: Demo for timer.

9 ** Input: NONE

10 ** Output: NONE

11 ** Created by: Chenxibing

12 ** Created Date: 2005-12-29

13 ** tasks **-----------------------------------------------------------------------------------------------------

14 ** Modified:

15 ** Modified Date:

16 ** shards **-----------------------------------------------------------------------------------------------------

17 *************************************** **************************************** ************************

18 */

19 int limit = 10;

20/* signal process */

21 void timeout_info (int signo)

22 {

23 if (limit = 0)

24 {

25 printf ("Sorry, time limit reached. \ n ");

26 return;

27}

28 printf ("only % d senconds left. \ n", limit --);

29}

30

31/* init sigaction */

32 void init_sigaction (void)

33 {

34 struct sigaction act;

35

36 act. sa_handler = timeout_info;

37 act. sa_flags = 0;

38 sigemptyset (& act. sa_mask );

39 sigaction (SIGPROF, & act, NULL );

40}

41

42/* init */

43 void init_time (void)

44 {

45 struct itimerval val;

46

47 val. it_value. TV _sec = 1;

48 val. it_value. TV _usec = 0;

49 val. it_interval = val. it_value;

50 setitimer (ITIMER_PROF, & val, NULL );

51}

52

53

54 int main (void)

55 {

56 init_sigaction ();

57 init_time ();

58 printf ("You have only 10 seconds for thinking. \ n ");

59

60 while (1 );

61 return 0;

62}

63

The usage of ITIMER_VIRTUAL and ITIMER_PROF is similar. when you set the timer in setitimer to ITIMER_VIRTUAL, you change SIGALRM in sigaction to SIGVTALARM. Similarly, ITIMER_PROF corresponds to SIGPROF.

However, you may notice that when you use ITIMER_VIRTUAL and ITIMER_PROF, you get a stopwatch and you will find that the time interval between the output string of the program is more than 2 seconds, it may even take 5 to 6 seconds to output one. As for the reason, you have to think about it. ^_^

Sleep

Next, let's take a look at how to implement scheduled task execution with sleep and usleep.

# Include

# Include

# Include

# Include

 

Static char msg [] = "I need ed 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);/* sleep for 2 seconds */

/* Send signals to the main process. In fact, they send signals to themselves */

Sigqueue (getpid (), 50, tsval );

}

Return 0;

}

You can see that this is much simpler than the above, and you can test it with a stopwatch, the time is very accurate, specify 2 seconds to output a string for you. Therefore, this method is the easiest if you only perform a task at the regular time.

Time difference

Let's take a look at the timing by calculating the time difference:

 

# Include

# Include

# Include

# Include

# Include

 

Static char msg [] = "I need ed 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;

/* Get the current time */

Time (& nowtime );

/* Compare with the previous time. if the value is greater than or equal to 2 seconds, the system sends a signal immediately */

If (nowtime-lasttime> = 2)

{

/* Send signals to the main process. In fact, they send signals to themselves */

Sigqueue (getpid (), 50, tsval );

Lasttime = nowtime;

}

}

Return 0;

}

This is different from the above in that it is manually calculated by yourself. if you want to calculate the time difference more accurately, you can replace the time function with gettimeofday, which can be precise to the subtle.

The timing methods described above are different in terms of timing efficiency, method, and time accuracy. what method is used depends on your program needs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.