settimer in vc++

Posted on 2009-02-17
Last Modified: 2012-05-06
I have written code in vc++ using timer
my aim is it has to print the numbers until the time expires ex 10 seconds
but it is printitng only 0 and then after ten seconds i have seen the timer proc function called

please let me  know what is wrong?

i have to print values  until time expires
// timer.cpp : Defines the entry point for the console application.


#include "stdafx.h"

#include <windows.h>

#include <stdio.h>

bool bStillBusy = false;


void mynum();

int main()


 UINT id;

 MSG msg;

bStillBusy  = true;

 id = SetTimer(NULL, 0, 10000, (TIMERPROC) TimerProc);





	GetMessage(&msg, NULL, 0, 0);




 KillTimer(NULL, id);

 return 0;


void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime) 


printf("Timer func got called\n");

bStillBusy = false;


void mynum()


int k = 0;

if( k < 50)




	 k =k+1;


Open in new window

Question by:hp746
    LVL 10

    Expert Comment

    try making the printing take more time

    void mynum()
    int k = 0;
    if( k < 5000)
                   if(k mod 100 == 0)
             k =k+1;
    LVL 8

    Expert Comment

    This is a console application , so it doesn't have a message loop , don't use
    GetMessage(&msg, NULL, 0, 0);

    Use Sleep(1) instead...
    LVL 86

    Accepted Solution

    Theoretically, that should work. The catch is that even if you specify a 'TimerProc()', your app will still need a message loop in order for 'SetTimer()' to work (there used to be a MSDN article that stated "SetTimer() was not designed to be used with a console application because it requires a message loop to dispatch the timer signal to the timer procedure. In a console application, this behavior can be easily emulated with a thread that is set to wait on an event.". The options now are to either create a thread that periodically triggers the code that you want to be executed periodically or use 'CreateWaitableTimer()' instead. For the latter, see ("How To Use a Waitable Timer with an Asynchronous Procedure Call"). I''ll attach code snippets for both options
    // thread
    #include <windows.h>
    #ibclude <stdio.h>
    DWORD WINAPI My30SecWaitThread ( LPVOID) {
    // do something after 30mins
      Sleep ( 30 * 1000);
      printf("Time Out");
    void main () {
      DWORD dwTID;
      CreateThread(NULL,0,My30SecWaitThread, 0, 0, &dwTID);
      Sleep(60 * 1000);
    // waitable timer
       #define _WIN32_WINNT 0x0400
       #include <windows.h>
       #include <stdio.h>
       #define _SECOND 10000000
       typedef struct _MYDATA {
         TCHAR *szText;
         DWORD dwValue;
       } MYDATA;
       VOID CALLBACK TimerAPCProc(
           LPVOID lpArg,               // Data value.
           DWORD dwTimerLowValue,      // Timer low value.
           DWORD dwTimerHighValue ) {  // Timer high value.
         MYDATA *pMyData = (MYDATA *)lpArg;
         printf( "Message: %s\nValue: %d\n\n", pMyData->szText,
           pMyData->dwValue );
       void main( void ) {
         HANDLE          hTimer;
         BOOL            bSuccess;
         __int64         qwDueTime;
         LARGE_INTEGER   liDueTime;
         MYDATA          MyData;
         TCHAR           szError[255];
         MyData.szText = "This is my data.";
         MyData.dwValue = 100;
         if ( hTimer = CreateWaitableTimer(
               NULL,                   // Default security attributes.
               FALSE,                  // Create auto-reset timer.
               "MyTimer" ) ) {         // Name of waitable timer.
           __try {
             // Create a negative 64-bit integer that will be used to
             // signal the timer 5 seconds from now.
             qwDueTime = -5 * _SECOND;
             // Copy the relative time into a LARGE_INTEGER.
             liDueTime.LowPart  = (DWORD) ( qwDueTime & 0xFFFFFFFF );
             liDueTime.HighPart = (LONG)  ( qwDueTime >> 32 );
             bSuccess = SetWaitableTimer(
               hTimer,                 // Handle to the timer object.
               &liDueTime,             // When timer will become signaled.
               2000,                   // Periodic timer interval of 2 seconds.
               TimerAPCProc,           // Completion routine.
               &MyData,                // Argument to the completion routine.
               FALSE );                // Do not restore a suspended system.
             if ( bSuccess ) {
               for ( ; MyData.dwValue < 1000; MyData.dwValue += 100 ) {
                   INFINITE,           // Wait forever.
                   TRUE );             // IMPORTANT!!! The thread must be in an
                                       // alertable state to process the APC.
             } else {
               wsprintf( szError, "SetWaitableTimer() failed with Error %d.",
                 GetLastError() );
               MessageBox( NULL, szError, "Error", MB_ICONEXCLAMATION );
           } __finally {
             CloseHandle( hTimer );
         } else {
           wsprintf( szError, "CreateWaitableTimer() failed with Error %d.",
             GetLastError() );
           MessageBox( NULL, szError, "Error", MB_ICONEXCLAMATION );

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Article by: SunnyDark
    This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
    Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
    The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

    779 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

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now