Click here to Skip to main content
13,045,540 members (70,963 online)
Click here to Skip to main content
Add your own
alternative version


39 bookmarked
Posted 20 Aug 2003

How to use SetTimer() with callback to a non-static member function

, 20 Aug 2003
Rate this:
Please Sign up or sign in to vote.
This article describes how to use SetTimer() with a non-static member function as the callback.

Quick update...

After reviewing the comments and suggestions from a few people, I made the solution better. Look for an update to this article which uses a better approach, namely using the functions:

  • CreateWaitableTimer()
  • SetWaitableTimer()
  • WaitForMultipleObjects()

The solution based on these functions will allow multiple instances of the CSleeperThread class to run (instead of just one using the current example). So stay tuned, I'll have this article updated as soon as possible. :-)


I have seen many questions on the boards about how to properly use SetTimer(). I've also noticed that most of these questions are around how to put a thread to sleep for X seconds. One obvious answer would be to use the Sleep() function. The main drawback is, how do you gracefully shut down your thread, or cancel the Sleep() operation before the time expires.

This article is meant to address all of the above. I give an example of putting a thread to sleep using SetTimer(). The SetTimer() calls back to a non-static function. This is key, because normally you have to pass a static member to SetTimer() which means it can't access any other non-static variables or member functions of the class.


Since implementing a non-static callback member is key to this, we'll go into this first. Implementing a callback to a static member function doesn't require anything different from implementing a regular C callback function. Since static member functions have the same signature as C functions with the same calling conventions, they can be referenced using just the function name.

Making a non-static callback member function is a different story, because they have a different signature than a C function. To make a non-static member function, it requires the use of two additional items:

  • A global (void*) pointer, referencing the class of the callback function
  • A wrapper function which will be passed to SetTimer()

This is actually a fairly simple implementation. First, you need to define your class:

class CSleeperThread : public CWinThread {
  static VOID CALLBACK TimerProc_Wrapper( HWND hwnd, UINT uMsg, 
                                  UINT idEvent, DWORD dwTime );
  VOID CALLBACK TimerProc( HWND hwnd, 
                       UINT uMsg, UINT idEvent, DWORD dwTime );
  void ThreadMain();
  void WakeUp();
  static void * pObject;
  UINT_PTR pTimer;

Then, don't forget to include the following line in your class implementation file:

void * CSleeperThread::pObject;

Now that we have our class declared, we can look at the wrapper function, the non-static member function and the member function that will call SetTimer():

VOID CALLBACK CSleeperThread::TimerProc_Wrapper( HWND hwnd, UINT uMsg, 
                                           UINT idEvent, DWORD dwTime ) {
 CSleeperThread *pSomeClass = (CSleeperThread*)pObject; // cast the void pointer
 pSomeClass->TimerProc(hwnd, uMsg, idEvent, dwTime); // call non-static function

The wrapper function first initializes a CSleeperThread pointer with pObject. Since pSomeClass is a local pointer, we can access it within the static wrapper function.

VOID CALLBACK CSleeperThread::TimerProc(HWND hwnd, 
     UINT uMsg, UINT idEvent, DWORD dwTime) {
 if(idEvent == pTimer) {
   KillTimer(NULL, pTimer);  // kill the timer so it won't fire again
   ResumeThread();  // resume the main thread function

The TimerProc member function isn't static, so we can access other non-static functions like ResumeThread() and we can access the private variable lock. Notice that I've entered a critical section which prevents a second timer event to enter the callback, thus ensuring that the first execution of TimerProc() will cancel out the timer.

Next, let's take a look at the main execution function, ThreadMain().

void CSleeperThread::ThreadMain()
  pObject = this; // VERY IMPORTANT, must be initialized before
                  // calling SetTimer()
  // call SetTimer, passing the wrapper function as the callback
  pTimer = SetTimer(NULL, NULL, 10000, TimerProc_Wrapper);
  // suspend until the timer expires
  // the timer has expired, continue processing 

The first step in ThreadMain() is absolutely critical. We need to assign the class instance pointer (this) to the pObject variable. This is how the wrapper callback function will gain access to execute the non-static member function.

Next, we just call SetTimer() passing in a function pointer to our wrapper function. SetTimer() will call the wrapper function when the timer expires. The wrapper function in turn, will execute the non-static function TimerProc(), by accessing the static variable pSomeClass.

NOTE: I chose to implement a main function that will create the timer, go to sleep, continue processing and then exit when finished. This is in effect a function that will only execute once per timer. You could easily add a loop to ThreadMain() which would execute once for each timer event.

One last little function. Since we used SuspendThread() in ThreadMain(), if we need to wake up the thread (for whatever reason), all we have to do is make a call to ResumeThread(). So, I've added an access function like so:

void WakeUp() {
  KillTimer(NULL, pTimer);
  ResumeThread(); // wake the thread up

Buh dee buh dee, that's all folks...

And there we have it. A thread safe class that goes to sleep using SetTimer() and a non-static callback function; which also has the ability to wake up before the timer expires.

Hopefully, you have found this helpful. I've actually used this code in a project I'm working on now, and was in hopes someone else would get some good use out of it.

Someone once told me "you'll like programming if you like banging your head against the wall repeatedly". I've found that to be true, it took me literally several days to figure out what I've put into this article, I'm just slow I guess.

Whew, my head hurts, time for some Advil...or Ibooprofin.. or asssprin.... or something.


I probably learned way more in the process of writing this article. So, much thanks goes to Lars Haendel for creating a web-site dedicated to understanding function pointers, without which I wouldn't know didley.


This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


About the Author

Software Developer (Senior) In Of Eight
United States United States
Became hooked on programming in the 3rd grade using basic. Programming in C/C++ since 1997.

This year I worked on a three person team to create a distributed computing system that predicts stock prices using an Artificial Neural Network. We used Encog as the ANN framework and Scoop as the distributed computing framework.

Prior to that, I created a proof of concept augmented reality game engine that runs on mobile platforms. The aim of that project was to create a MMO augmented reality system that would allow users to create their own game scenarios and virtual worlds in an augmented reality space. The project was coded using Objective-C, OpenGL, REST web-services and MySQL.

Fluent in the following languages and frameworks:
C / C++
FANN (ANN Framework)
Encog (ANN Framework)
Scoop (Distributed Computing Framework as a Python module)
iOS Framework

For a copy of a resume, please find my personal web-site at:

You may also be interested in...


Comments and Discussions

GeneralSetTimer Callback Pin
restricted17-Oct-08 6:22
memberrestricted17-Oct-08 6:22 
GeneralSetTimer never fires Pin
MForceOne11-Jun-08 4:56
memberMForceOne11-Jun-08 4:56 
GeneralRe: SetTimer never fires Pin
Nirupama Ravi28-Jul-08 20:49
memberNirupama Ravi28-Jul-08 20:49 
GeneralRe: SetTimer never fires Pin
AleiZ19-Aug-08 3:49
memberAleiZ19-Aug-08 3:49 
GeneralRe: SetTimer never fires - Service won't run it's Callbacks Pin
CodeAssi5-Feb-09 1:05
memberCodeAssi5-Feb-09 1:05 
GeneralSuspendThread() cause "Debug Assertion Failed!", why Pin
suna59922-May-07 5:43
membersuna59922-May-07 5:43 
QuestionMultiple Client Calling without Mapping? Pin
Green_Light13-Oct-06 11:30
memberGreen_Light13-Oct-06 11:30 
AnswerRe: Multiple Client Calling without Mapping? Pin
Imran_Ansari7-Feb-07 22:13
memberImran_Ansari7-Feb-07 22:13 
GeneralUse of SetTimer() with callback to multiple clients Pin
Imran_Ansari6-Jun-06 21:06
memberImran_Ansari6-Jun-06 21:06 
GeneralThe almost correct solution Pin
rezzzman17-Feb-06 11:17
memberrezzzman17-Feb-06 11:17 
GeneralSetTimer Pin
subhashkjain2001@hotmail.com27-Dec-04 23:06
membersubhashkjain2001@hotmail.com27-Dec-04 23:06 
QuestionHow can i use these code? Pin
reinkorea17-Jun-04 8:17
memberreinkorea17-Jun-04 8:17 
AnswerRe: How can i use these code? Pin
mellertson17-Jun-04 8:40
membermellertson17-Jun-04 8:40 
QuestionRe: How can i use these code? Pin
MForceOne10-Jun-08 13:44
memberMForceOne10-Jun-08 13:44 
GeneralGood but question Pin
ROLKI___18-Apr-04 6:40
memberROLKI___18-Apr-04 6:40 
GeneralRe: Good but question Pin
Green_Light13-Oct-06 11:24
memberGreen_Light13-Oct-06 11:24 
GeneralBad solution Pin
Jean-Michel LE FOL20-Aug-03 22:09
memberJean-Michel LE FOL20-Aug-03 22:09 
GeneralIt's a good solution Pin
billgatest21-Aug-03 4:54
memberbillgatest21-Aug-03 4:54 
GeneralRe: Bad solution Pin
Mike Ellertson21-Aug-03 5:45
sussMike Ellertson21-Aug-03 5:45 
GeneralRe: Bad solution Pin
Paolo Messina21-Aug-03 7:23
memberPaolo Messina21-Aug-03 7:23 
GeneralRe: Bad solution Pin
mellertson21-Aug-03 8:31
membermellertson21-Aug-03 8:31 
GeneralRe: Bad solution Pin
Paolo Messina21-Aug-03 14:34
memberPaolo Messina21-Aug-03 14:34 
GeneralRe: Bad solution Pin
Zele21-Mar-04 23:53
memberZele21-Mar-04 23:53 
GeneralRe: Bad solution Pin
JaeWook Choi8-Nov-04 8:27
memberJaeWook Choi8-Nov-04 8:27 

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 | Terms of Use | Mobile
Web01 | 2.8.170713.1 | Last Updated 21 Aug 2003
Article Copyright 2003 by Mikey_E
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid