Simple timer for games
This article presents a simple timer class suitable for games. This class uses CIdle to generate the timing events.
The CIdle class is an active object that runs whenever there are no other active objects with higher priority ready to run. Different from other approaches found in the Symbian OS API, CIdle does not use a predefined time interval to generate events.
Defining the class
Here is the class declaration:
class CCustomTimer : public CBase
// Creates an instance of this class. MTimerListener
// is an object interested in handling the timer event.
static CCustomTimer* NewL (MTimerListener & aListener);
// Starts the timer.
void Start ();
// Cancels the timer.
void Cancel ();
// Callback used internally to notify the listener.
// Required by CIdle.
static TInt IdleCallBack (TAny* aPtr);
// Constructor, stores the reference to the listener
CCustomTimer (MTimerListener & aListener)
: iListener (& aListener)
// Second part of the two-phase constructor.
void ConstructL ();
MTimerListener * iListener; // The object that handles the timer event.
The MTimerListener interface is defined as follows:
virtual void OnTimer () = 0;
The CCustomTimer class implementation is defined this way:
void CCustomTimer::ConstructL ()
iIdle = CIdle::NewL (CIdle::EPriorityIdle);
void CCustomTimer::Start ()
if (!iIdle->IsActive () )
iIdle->Start (TCallBack (IdleCallBack, this) );
void CCustomTimer::Cancel ()
TInt CCustomTimer::IdleCallBack (TAny* aPtr)
CCustomTimer* me = ((CCustomTimer*)aPtr);
// Suppose we plan the game to run at 30 frames per second. Then, we
// need to calculate the required time step to meet this requisite.
// (time in microseconds)
const TInt KTargetTimeStep = 1000000 / 30;
void MyGame::OnTimer ()
// Handle input.
// Now we are going to calculate how many steps the game should process,
// so it is not late.
// Keep current time.
// Calculate elapsed time since the last update.
// The iStartTime variable is a member of the MyGame class.
TInt elapsed = I64LOW (time.MicroSecondsFrom (iStartTime).Int64());
// Update total game time. The iTotalTime variable
// is also a member of the MyGame class.
iTotalTime += elapsed;
// Calculate how many updates should be processed. Notice that the
// division is an integer division (it means 5 / 2 = 2).
elapsed = iTotalTime / KTargetTimeStep;
for (TInt i = 0; i < elapsed; ++i)
// Subtract the time steps processed.
iTotalTime -= elapsed * KTargetTimeStep;
iStartTime = time.Int64();