Timer in C

Posted on 2013-09-18
Medium Priority
Last Modified: 2013-10-08
Hi there,

I need to have a simple timer that can do the following.  The timer should call a callback function once the timer expires.  Also, I should be able to stop it.  I want it to be in C.  Can someone provide some example.  thank you.
Question by:ambuli
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39503160
Is this school work?

Author Comment

ID: 39503235
No:-) I am out of school for many years.  

I tried alarm() and it works, but I want a way to cancel the timer.  thanks.
LVL 33

Expert Comment

ID: 39503467
Haven't done this in Linux, but I found this for you:
— Function: unsigned int alarm (unsigned int seconds)

The alarm function sets the real-time timer to expire in seconds seconds. If you want to cancel any existing alarm, you can do this by calling alarm with a seconds argument of zero.

The return value indicates how many seconds remain before the previous alarm would have been sent. If there is no previous alarm, alarm returns zero.
A proven path to a career in data science

At Springboard, we know how to get you a job in data science. With Springboard’s Data Science Career Track, you’ll master data science  with a curriculum built by industry experts. You’ll work on real projects, and get 1-on-1 mentorship from a data scientist.

LVL 33

Expert Comment

ID: 39503493
This may be closer to what you are looking for:
alarm(3) - Linux man page
If seconds is 0, a pending alarm request, if any, is canceled.
LVL 40

Assisted Solution

omarfarid earned 1000 total points
ID: 39503805
I have done this on solaris long time ago, and here is the code:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>

static void act() ;

char line[80] ;
int  rem_time ;
jmp_buf env ;

      signal(SIGALRM , act) ;
      if (setjmp(env) == 0)
            alarm(10) ;
            printf("Enter your name: ") ;
            fgets(line , 80 , stdin) ;
      rem_time=alarm(0) ;
      printf("\n%s ; response time is : %d\n" , line , 10 - rem_time) ;

void act()
      strcpy(line , " missed it !!!") ;
      longjmp(env , 1) ;
LVL 86

Accepted Solution

jkr earned 1000 total points
ID: 39506554
Apart from 'alarm()', there's also 'setitimer()' (http://linux.about.com/library/cmd/blcmdl2_setitimer.htm), e.g.

#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <errno.h>

#define LOOP_LIMIT  0x0000ffff

volatile int sigcount=0;

void catcher( int sig ) {

    struct itimerval value;
    int which = ITIMER_REAL;

    printf( "Signal catcher called for signal %d\n", sig );

    if( sigcount > 1 ) {

         * Disable the real time interval timer

        getitimer( which, &value );

        value.it_value.tv_sec = 0;
        value.it_value.tv_usec = 0;

        setitimer( which, &value, NULL );

int main( int argc, char *argv[] ) {

    int result = 0;

    struct itimerval value, ovalue, pvalue;
    int which = ITIMER_REAL;

    struct sigaction sact;
    volatile double count;
    time_t t;

    sigemptyset( &sact.sa_mask );
    sact.sa_flags = 0;
    sact.sa_handler = catcher;
    sigaction( SIGALRM, &sact, NULL );

    getitimer( which, &pvalue );

     * Set a real time interval timer to repeat every 200 milliseconds

    value.it_interval.tv_sec = 0;        /* Zero seconds */
    value.it_interval.tv_usec = 200000;  /* Two hundred milliseconds */
    value.it_value.tv_sec = 0;           /* Zero seconds */
    value.it_value.tv_usec = 500000;     /* Five hundred milliseconds */

    result = setitimer( which, &value, &ovalue );

     * The interval timer value returned by setitimer() should be
     * identical to the timer value returned by getitimer().

    if( ovalue.it_interval.tv_sec != pvalue.it_interval.tv_sec  ||
        ovalue.it_interval.tv_usec != pvalue.it_interval.tv_usec ||
        ovalue.it_value.tv_sec != pvalue.it_value.tv_sec ||
        ovalue.it_value.tv_usec != pvalue.it_value.tv_usec ) {
        printf( "Real time interval timer mismatch\n" );
        result = -1;

    time( &t );
    printf( "Before loop, time is %s", ctime(&t) );

    for( count=0; ((count<LOOP_LIMIT) && (sigcount<2)); count++ );

    time( &t );
    printf( "After loop, time is %s\n", ctime(&t) );

    if( sigcount == 0 )
        printf( "The signal catcher never gained control\n" );
        printf( "The signal catcher gained control\n" );

    printf( "The value of count is %.0f\n", count );

    return( result );

Open in new window

(code taken from http://publib.boulder.ibm.com/iseries/v5r1/ic2924/index.htm?info/apis/setitime.htm)

Featured Post

7 new features that'll make your work life better

It’s our mission to create a product that solves the huge challenges you face at work every day. In case you missed it, here are 7 delightful things we've added recently to monday to make it even more awesome.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

I. Introduction There's an interesting discussion going on now in an Experts Exchange Group — Attachments with no extension . This reminded me of questions that come up here at EE along the lines of, "How can I tell the type of file from its cont…
Can you run Linux on a Windows system?  Yep.  Here's how.
Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

600 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question