Using a manual-reset timer

The following example shows how to use a manual-reset timer to control the length of the job performed by a task. When the job is too long, the task with higher priority will run and then terminate task performing a job.

#include <stdio.h>
#include <stdlib.h>
#include "OS_API.h"


HANDLE TimerHandle;
HANDLE WorkerTaskHandle;


ERROR WorkerTask(PVOID Arg)
{
  TIME JobTime;

  /* Mark parameter as unused */
  AR_UNUSED_PARAM(Arg);

  /* Initialize random number generator */
  srand((unsigned) arGetTickCount());

  /* Infinite loop */
  while(1)
  {
    /* Perform work of varying length (from 100 up to 1100 miliseconds) */
    JobTime = 100 + rand() % 1001;
    printf("Job started for %lu ms... ", JobTime);
    osSleep(JobTime * AR_TICKS_PER_SECOND / 1000);
    printf("done.\n");

    /* Reset the timer */
    osResetTimer(TimerHandle);
  }
}


ERROR ControlTask(PVOID Arg)
{
  /* Mark parameter as unused */
  AR_UNUSED_PARAM(Arg);

  /* Configure timer and wait for it */
  osSetTimer(TimerHandle, AR_TICKS_PER_SECOND, 0);
  osWaitForObject(TimerHandle, OS_INFINITE);

  /* When waits exits, it means that the job is performing too long */
  osTerminateTask(WorkerTaskHandle);
  printf("\nWorker task has been terminated.\n");
  return ERR_NO_ERROR;
}


int main(void)
{
  /* Initialization */
  arInit();
  stInit();
  osInit();

  /* Create objects */
  TimerHandle = osCreateTimer(NULL, TRUE);
  osCreateTask(ControlTask, NULL, 0, 0, FALSE);
  WorkerTaskHandle = osCreateTask(WorkerTask, NULL, 0, 1, FALSE);

  /* Start the operating system */
  osStart();

  /* Deinitialization */
  osDeinit();
  arDeinit();
  return 0;
}

The result on the console should look as follows:

Job started for 247 ms... done.
Job started for 318 ms... done.
Job started for 100 ms... done.
Job started for 734 ms... done.
Job started for 928 ms... done.
Job started for 952 ms... done.
Job started for 482 ms... done.
Job started for 524 ms... done.
Job started for 1047 ms...
Worker task has been terminated.
SpaceShadow documentation