导读:
这是一个看似简单,但是很复杂的问题,因为windows使用WM_TIMER,但是console下没有Hwnd,没有消息分发器,不象unix下可以用alarm信号定时执行某个函数,不知道java是如何实现的。
想起masterz曾经给出过例子,自从做java后,再也没有见过他。其实这个也不难,但首先要保证你的定时器要在一个线程中设置,如果你用MFC,那么在控制台中你可以从CWinThread派生一个类,然后在这个类中设置定时器,但不像CWnd类中的定时器那么好用。
user timer in workthread of console app
#include
#include
#include
unsigned long WINAPI Thread(PVOID pvoid);
void main()
{
DWORD dwThreadId;
printf("use timer in workthread of console application /n");
HANDLE hThread = CreateThread(
NULL, // no security attributes
0, // use default stack size
Thread, // thread function
0, // argument to thread function
0, // use default creation flags
&dwThreadId);
DWORD dwwait=WaitForSingleObject(hThread,1000*30);
switch(dwwait)
{
case WAIT_ABANDONED:
printf("main thread WaitForSingleObject return WAIT_ABANDONED/n");
break;
case WAIT_OBJECT_0:
printf("main thread WaitForSingleObject return WAIT_OBJECT_0/n");
break;
case WAIT_TIMEOUT:
printf("main thread WaitForSingleObject return WAIT_TIMEOUT/n");
break;
}
CloseHandle(hThread);
_getch();
}
unsigned long WINAPI Thread(PVOID pvoid)
{
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
UINT timerid=SetTimer(NULL,111,3000,NULL);
BOOL bRet;
int count =0;
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
if(msg.message==WM_TIMER)
{
count++;
printf("WM_TIMER in work thread count=%d/n",count);
if(count>4)
break;
}
else
这是一个看似简单,但是很复杂的问题,因为windows使用WM_TIMER,但是console下没有Hwnd,没有消息分发器,不象unix下可以用alarm信号定时执行某个函数,不知道java是如何实现的。
想起masterz曾经给出过例子,自从做java后,再也没有见过他。其实这个也不难,但首先要保证你的定时器要在一个线程中设置,如果你用MFC,那么在控制台中你可以从CWinThread派生一个类,然后在这个类中设置定时器,但不像CWnd类中的定时器那么好用。
user timer in workthread of console app
#include
#include
#include
unsigned long WINAPI Thread(PVOID pvoid);
void main()
{
DWORD dwThreadId;
printf("use timer in workthread of console application /n");
HANDLE hThread = CreateThread(
NULL, // no security attributes
0, // use default stack size
Thread, // thread function
0, // argument to thread function
0, // use default creation flags
&dwThreadId);
DWORD dwwait=WaitForSingleObject(hThread,1000*30);
switch(dwwait)
{
case WAIT_ABANDONED:
printf("main thread WaitForSingleObject return WAIT_ABANDONED/n");
break;
case WAIT_OBJECT_0:
printf("main thread WaitForSingleObject return WAIT_OBJECT_0/n");
break;
case WAIT_TIMEOUT:
printf("main thread WaitForSingleObject return WAIT_TIMEOUT/n");
break;
}
CloseHandle(hThread);
_getch();
}
unsigned long WINAPI Thread(PVOID pvoid)
{
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
UINT timerid=SetTimer(NULL,111,3000,NULL);
BOOL bRet;
int count =0;
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
if(msg.message==WM_TIMER)
{
count++;
printf("WM_TIMER in work thread count=%d/n",count);
if(count>4)
break;
}
else