Timers¶
For most MiraOS applications, timers will be essential. The timers are used for checking if a time period has passed, scheduling tasks, etc. The timers are also used by applications to let the OS work with other things or enter low power mode for a time period before resuming execution.
Event timers¶
An event timer, or etimer
, is used for scheduling processes to be executed after a period of time. Etimers are used in processes to wait for a time period while the rest of the system can work or enter low power mode. An etimer will send an event to the process when it expires.
Example 1¶
In the following example an etimer is used to pause the execution of the current process for one second before it continues.
This is done in these steps:
- Defining a etimer variable (note: this must be static to preserve it over context switches).
- Setting the etimer with the
etimer_set(...)
call. An event will be generated when timer expires. - Telling the process to wait for an event.
PROCESS_THREAD(test_hello, ev, data)
{
/* An event-timer variable. Note that this variable must be static
in order to preserve the value across yielding. */
static struct etimer et;
PROCESS_BEGIN();
while (1) {
etimer_set(&et, CLOCK_SECOND); /* Set the timer to 1 second. */
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
printf("Hello, world!\n");
}
PROCESS_END();
}
Example 2¶
The second example will use two etimers, one to print a character every 0.5 seconds, and one that prints a newline every 10 seconds.
PROCESS_THREAD(test_print, ev, data)
{
/* Our two timer variables */
static struct etimer et, et2;
PROCESS_BEGIN();
etimer_set(&et, CLOCK_SECOND / 2); /* Set the timer to 0.5 seconds. */
etimer_set(&et2, CLOCK_SECOND * 10); /* Set the timer to 10 seconds. */
while (1) {
PROCESS_WAIT_EVENT(); /* wait for any event */
if (etimer_expired(&et)) {
etimer_set(&et, CLOCK_SECOND / 2); /* reset the timer */
printf(".");
}
if (etimer_expired(&et2)) {
etimer_set(&et2, CLOCK_SECOND * 10); /* reset the timer */
printf("\n");
}
}
PROCESS_END();
}