We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

settimer in vc++

hp746
hp746 asked
on
Medium Priority
1,192 Views
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 CALLBACK TimerProc(HWND, UINT, UINT, DWORD);
void mynum();
int main()
{
 UINT id;
 MSG msg;
 
bStillBusy  = true;
 
 id = SetTimer(NULL, 0, 10000, (TIMERPROC) TimerProc);
 
 while(bStillBusy) 
 {
	 
	mynum();
 
	GetMessage(&msg, NULL, 0, 0);
	DispatchMessage(&msg);
	
 }
 
 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)
	 {
		printf("%i\n",k);
 
	 }
 
	 k =k+1;
 
 
 
}

Open in new window

Comment
Watch Question

CERTIFIED EXPERT

Commented:
try making the printing take more time

void mynum()
{
 
int k = 0;
if( k < 5000)
         {
               if(k mod 100 == 0)
                printf("%i\n",k/100);
 
         }
 
         k =k+1;
 
 
 
}
This is a console application , so it doesn't have a message loop , don't use
GetMessage(&msg, NULL, 0, 0);
DispatchMessage(&msg);

Use Sleep(1) instead...
CERTIFIED EXPERT
Top Expert 2012
Commented:
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 () {
 
  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 );
     MessageBeep(0);
 
   }
 
 
   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 ) {
 
             SleepEx(
               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

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.