Symbian Developer Library

SYMBIAN OS V6.1 EDITION FOR C++

[Index] [Glossary] [Previous] [Next]



How to start a periodic timer

A periodic timer, CPeriodic, invokes a function at regular intervals. You must wrap the function to be called in a TCallBack.

First, we provide a callback function for the timer to call. The callback function can be a static member, i.e. TInt X::Foo(TAny *) or global, i.e. TInt Foo(TAny *). The TAny* can point to any object that we specify when we start the timer.

It is awkward to deal with TAny*, and more convenient to write handler code from a non-static member function, so here we code a static function to invoke a non-static function DoTick() as follows:

TInt CPeriodicRunner::Tick(TAny* aObject)
    {
    // cast, and call non-static function
    ((CPeriodicRunner*)aObject)->DoTick();
    return 1;
    }

The next piece of code creates a CPeriodic and sets it off with one-second ticks. The callback is specified to call the static Tick() function, passing the this pointer (which we use in Tick() to call DoTick()).

void CPeriodicRunner::StartTimer()
    {
    const TInt tickInterval=1000000;
    iPeriodic=CPeriodic::NewL(0); // neutral priority
    iPeriodic->StartInMicroSeconds(tickInterval,tickInterval,TCallBack(Tick, this));
    }