[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


settimer in vc++

Posted on 2009-02-17
Medium Priority
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

ID: 23667587
try making the printing take more time

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

Expert Comment

ID: 23667732
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

jkr earned 1500 total points
ID: 23672742
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 http://support.microsoft.com/kb/184796 ("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 () {
  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;
       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


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses

873 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