Createwaitabletimer and setwaitabletimer functions (timer)

Source: Internet
Author: User

Users feel that the software is easy to use, that is, they can do some work on a regular basis without the need to participate. For example, update the virus database regularly every day, regularly download movies, and regularly update characters in the game. To implement these functions, you can use the API functions createwaitabletimer and setwaitabletimer of the timer to implement them. This is more accurate for the clock created by the API function, and can reach 100 times the second of the second.
 
The createwaitabletimer and setwaitabletimer functions are declared as follows:
 
Winbaseapi
_ Out
Handle
Winapi
Createwaitabletimera (
_ In_opt lpsecurity_attributes lptimerattributes,
_ In bool bmanualreset,
_ In_opt lpcstr lptimername
);
Winbaseapi
_ Out
Handle
Winapi
Createwaitabletimerw (
_ In_opt lpsecurity_attributes lptimerattributes,
_ In bool bmanualreset,
_ In_opt lpcwstr lptimername
);
# Ifdef Unicode
# Define createwaitabletimer createwaitabletimerw
# Else
# Define createwaitabletimer createwaitabletimera
# Endif //! Unicode
 
 
Winbaseapi
Bool
Winapi
Setwaitabletimer (
_ In handle htimer,
_ In const large_integer * lpduetime,
_ In long lperiod,
_ In_opt ptimerapcroutine pfncompletionroutine,
_ In_opt lpvoid lpargtocompletionroutine,
_ In bool fresume
);
 
Lptimerattributes is the attribute used to set the timer.
Whether to manually reset bmanualreset.
Lptimername is the name of the timer.
Htimer is the timer handle.
Lpduetime is used to set the timer time interval. When set to positive, it is absolute time; when set to negative, it is relative time.
Lperiod is a period.
Pfncompletionroutine is the set callback function.
Lpargtocompletionroutine is the parameter sent to the callback function.
Fresume is used to set whether the system is automatically restored.
 
An example of calling a function is as follows:
#001 // create a timer
#002 // Cai junsheng 2007/11/06 QQ: 9073204 Shenzhen
#003 int createtesttimer (void)
#004 {
#005 handle htimer = NULL;
#006 large_integer liduetime;
#007
#008 // set the relative time to 10 seconds.
#009 liduetime. quadpart =-100000000;
#010
#011; // create a timer.
#012 htimer = createwaitabletimer (null, true, _ T ("testwaitabletimer "));
#013 if (! Htimer)
#014 {
#015 return 1;
#016}
#017
#018 outputdebugstring (_ T ("10 seconds timer/R/N "));
#019
#020 // set to 10 seconds.
#021 if (! Setwaitabletimer (htimer, & liduetime, 0, null, null, 0 ))
#022 {
#023 //
#024 closehandle (htimer );
#025 return 2;
#026}
#027
#028 // The timer has a signal.

While (true)

{
#029 if (waitforsingleobject (htimer, infinite )! = Wait_object_0)
#030 {
#031 outputdebugstring (_ T ("10 seconds timer error/R/N "));
#032 //
#033 closehandle (htimer );
#034 return 3;
#035}
#036 else
#037 {
#038 // 10 seconds.

Setwaitabletimer (htimer, & liduetime, 0, null, null, 0); // reset the htimer information to no signal. Otherwise, the htimer will be output continuously.
#039 outputdebugstring (_ T ("10 seconds timer to/R/N"); // "10 seconds timer"
#040}
#041}
#042 //
#043 closehandle (htimer );
#044 return 0;
#045}


This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/jiangxinyu/archive/2008/07/23/2696447.aspx

Scheduled functions implemented by asynchronous program call (APC)

Compilation: Zhang haisu

A timer is a kernel object that is triggered at a specific time or rule interval. Asynchronous program calls with timers can allow the callback function to be executed when any timer is triggered. The sample code in this article shows how to implement it.
When using this timer, You need to define constant _ win32_winnt as 0x0400, and this constant should be defined before the package to ensure that the appropriate timer prototype function is declared.
You can create a timer by calling createwaitabletimer (). This function returns a handle pointing to the kernel object. If the timer already exists, you can use openwaitabletimer () to obtain a process-related handle. Whether it is a handle obtained through createwaitabletimer () or openwaitabletimer (), it must be released when no timer is required by using the closehandle () function ().
The scheduled time is set by calling setwaitabletimer () and can be set to a specific time point (for example, December 16,199 9 at PM) or a relative time (for example, every five minutes from now on ). The time parameter specified by the setwaitabletime () function must be of the large_integer type. The value must conform to the format described in the structure filetime. If the value is positive, it indicates a specific time. If the value is negative, it indicates the relative time in 100 nanoseconds. The following sample code uses relative time. After the setwaitabletimer () function is called, the timer is triggered every 5 seconds.
You can also set the timer to periodic self-excitation by passing a periodic parameter (in milliseconds) to the third parameter of setwaitabletimer ). When the second parameter of createwaitabletimer () is passed false, a timer with auto return can be generated. In this example, set a two-second timer.
After the timer is set, you can combine the APC with it. Here we call the APC function a complete routine. The address of the complete routine is the fourth parameter of setwaitabletimer. The fifth parameter is a null pointer. You can use it to pass complete routine parameters.
In all APC instances, to execute a full routine, the thread must be in the listening state. The full routine will always be executed by the same thread that calls setwaitabletimer (). Therefore, this thread must be in the listening state. You can call any of the following listening functions to set the listening status:

  • Sleepex ();
  • Waitforsingleobjectex ();
  • Waitformultipleobjectsex ();
  • Msgwaitformultipleobjectsex ();
  • Signalobjectandwait ();

Each thread has an APC queue. When calling any of the above functions, if there is an entity in the APC queue of the thread, the thread will not enter the sleep state. Instead, we need to retrieve the entity from the APC queue, then, call the corresponding complete routine.
If no entity exists in the APC queue, the thread will be suspended until the conditions are met. Waiting conditions are met: An entity is added to the APC queue, timeout, activation handle, and so on, and when msgwaitformultipleobjectsex () is called, a message enters a message queue of the thread. If the waiting condition satisfies an entity in the APC queue, the thread will be activated and execute a complete routine. In this case, the return value of the function is wait_io_completion.

Important]

1. After a complete routine is executed, the system checks the remaining entities in APC for processing. A monitoring function returns only after processing all APC entities. Therefore, if an object is added to an APC queue faster than the processing speed, it may never be returned to call these functions. Especially when the scheduled wait time is shorter than the time required to execute the full routine, this situation is more likely to happen.
2. When the APC is used to implement the timer, the timer thread should not wait for the timer handle. If you wait for the timer handle, the thread is invoked because the timer is activated, instead of adding entities to the APC queue. At this time, the thread will no longer be in the listening state, so the complete routine will not be called. In this example, sleep () is used to place the thread in the listening state. After the timer is activated, if an entity is added to the APC queue of this thread, sleep () will wake up this thread.

[Sample Code]

#define _WIN32_WINNT 0x0500

#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 an 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 ); // Put thread in an alertable state
}

}
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 );
}
}

From: http://www.vckbase.com/document/viewdoc? Id = 1587

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.