Click here to Skip to main content
13,868,794 members
Click here to Skip to main content
Add your own
alternative version


44 bookmarked
Posted 15 Jan 2011
Licenced CPOL

Simple C++ Timer Wrapper

, 15 Jan 2011
Rate this:
Please Sign up or sign in to vote.
TemplateTimer: A convenient and simple MSVC / C++ timer wrapper for Windows using templates, where a class function can be easily specified for the timed event callback.


There are a wide variety of Windows timers available, this along with their different methods of implementation can make the task of including a simple timer into a piece of source code rather confusing, especially for someone new to C++. TemplateTimer does noting special but offers a convenient wrapper for the programmer who needs to implement a simple timer within a C++ class.

Code Discussion

In this implementation, CreateTimerQueueTimer() has been used as the timer but there are several different timers available. CreateTimerQueueTimer() has been implemented using WT_EXECUTEINTIMERTHREAD (for short tasks) but may be changed to suit specific requirements. It should be noted that this timer (as with all Windows timers) suffers from inherent non real-time OS inaccuracies. The performance is system dependent; however, after testing, the timer resolution was accurate around and above a 200ms interval.

The Start() method has two overloads. The default method simply allows the timer to be started with an interval in milliseconds. The first overload allows the timer to be started immediately (i.e., the first timed event is called immediately). The second overload allows the timer to be called only once.

The templated class TTimer implements a callback using templates. This allows the specification of a class function as the callback function through SetTimedEvent().

CTimer implements a virtual method OnTimedEvent() that is called by the timer procedure TimerProc(). TTimer derives from CTimer, and overrides the OnTimerEvent() method which in turn calls the (user defined) callback function.

GetCount() and SetCount() use InterlockedExchangeAdd() and InterlockedExchange() to provide a thread safe timer event count that can be read (or set) anywhere in the code. This use of InterlockedExchange() provides a convenient way of providing very quick mutex access to a number.

The Stop() method is used to stop the timer. If required, it can be used within the OnTimedEvent() function, for example to stop timer1 after 10 times (10 sec) use: if( timer1.GetCount() == 10 ){ timer1.Stop(); }.

Using the Code

For convenience, the TTimer and CTimer classes have been implemented in a single file (TemplateTimer.h). To use TemplateTimer, simply include TemplateTimer.h into your project and implement as shown in the test code TimerTest.cpp/.h.

'TemplateTimer.h' (see the 'Download source' link above)
#pragma once
#include <atlbase.h>

static void CALLBACK TimerProc(void*, BOOLEAN);

// class CTimer
class CTimer
        m_hTimer = NULL;
        m_mutexCount = 0;

    virtual ~CTimer()

    bool Start(unsigned int interval,   // interval in ms
               bool immediately = false,// true to call first event immediately
               bool once = false)       // true to call timed event only once
        if( m_hTimer )
            return false;


        BOOL success = CreateTimerQueueTimer( &m_hTimer,
                                              immediately ? 0 : interval,
                                              once ? 0 : interval,

        return( success != 0 );

    void Stop()
        DeleteTimerQueueTimer( NULL, m_hTimer, NULL );
        m_hTimer = NULL ;

    virtual void OnTimedEvent()
        // Override in derived class

    void SetCount(int value)
        InterlockedExchange( &m_mutexCount, value );

    int GetCount()
        return InterlockedExchangeAdd( &m_mutexCount, 0 );

    HANDLE m_hTimer;
    long m_mutexCount;

// TimerProc
void CALLBACK TimerProc(void* param, BOOLEAN timerCalled)
    CTimer* timer = static_cast<CTimer*>(param);
    timer->SetCount( timer->GetCount()+1 );

// template class TTimer
template <class T> class TTimer : public CTimer
    typedef private void (T::*TimedFunction)(void);

        m_pTimedFunction = NULL;
        m_pClass = NULL;

    void SetTimedEvent(T *pClass, TimedFunction pFunc)
        m_pClass         = pClass;
        m_pTimedFunction = pFunc;

    void OnTimedEvent()  
        if (m_pTimedFunction && m_pClass)

    T *m_pClass;
    TimedFunction m_pTimedFunction;

Here is the example code (see the 'Download demo project' link above).

#pragma once
#include "TemplateTimer.h"

class CTimerTest
    void RunTest();

    void OnTimedEvent1();
    void OnTimedEvent2();

    TTimer<CTimerTest> timer1 ;
    TTimer<CTimerTest> timer2 ;
#include "stdafx.h"
#include "TimerTest.h"

void CTimerTest::OnTimedEvent1()
    printf("\r\nTimer 1  Called (count=%i)", timer1.GetCount());

void CTimerTest::OnTimedEvent2()
    printf("\r\nTimer  2 Called (count=%i)", timer2.GetCount());

void CTimerTest::RunTest()
    printf("Hit return to start and stop timers");

    timer1.SetTimedEvent(this, &CTimerTest::OnTimedEvent1);
    timer1.Start(1000); // Start timer 1 every 1s

    timer2.SetTimedEvent(this, &CTimerTest::OnTimedEvent2);
    timer2.Start(2000); // Start timer 2 every 2s

    // Do something, in this case just wait for user to hit return   
    getchar();          // Wait for return (stop)

    timer1.Stop();      // Stop timer 1
    timer2.Stop();      // Stop timer 2

    printf("\r\nTimers stopped (hit return to exit)");
Example output



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionNice example Pin
malukhov28-Jun-18 4:42
membermalukhov28-Jun-18 4:42 
SuggestionSetCount/GetCount atomicity Pin
_groo_28-Mar-17 0:26
member_groo_28-Mar-17 0:26 
GeneralMy vote of 5 Pin
sprice865-Jul-15 13:34
professionalsprice865-Jul-15 13:34 
GeneralRe: My vote of 5 Pin
ken.loveday6-Jul-15 10:19
memberken.loveday6-Jul-15 10:19 
QuestionExcellent article! Pin
Mr.Darcy25-Dec-13 23:24
memberMr.Darcy25-Dec-13 23:24 
GeneralMy vote of 5 Pin
Rasmi Ranjan Nayak18-Mar-13 1:14
memberRasmi Ranjan Nayak18-Mar-13 1:14 
GeneralRe: My vote of 5 Pin
ken.loveday18-Mar-13 6:02
memberken.loveday18-Mar-13 6:02 
QuestionSmart, simple and efficient Pin
Joxemi18-Oct-11 1:05
memberJoxemi18-Oct-11 1:05 
GeneralMy vote of 5 Pin
qiguosheng4-May-11 5:08
memberqiguosheng4-May-11 5:08 
GeneralMy vote of 2 Pin
Wolfgang_Baron23-Jan-11 14:17
memberWolfgang_Baron23-Jan-11 14:17 
GeneralMy vote of 2 Pin
xComaWhitex17-Jan-11 7:28
memberxComaWhitex17-Jan-11 7:28 
GeneralRe: My vote of 2 Pin
xComaWhitex17-Sep-12 18:46
memberxComaWhitex17-Sep-12 18:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190214.1 | Last Updated 15 Jan 2011
Article Copyright 2011 by ken.loveday
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid