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
To implement these functions, you can use the timer API functions createwaitabletimer and setwaitabletimer.
The clock is relatively accurate and can reach 100 times the second of 1 billion.

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

AsynchronousProgramScheduled functions implemented by 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. Example Code 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 () obtains a process-related handle. Whether it is through createwaitabletimer ()
Or the handle obtained through openwaitabletimer (), which must be released when no timer is required by using the closehandle () function ().
Timing
The time is set by calling setwaitabletimer (). It can be set to a specific time point (such as December 16,199 9
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. This value should
This format conforms 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. In the following sample code
The relative time is used. After the setwaitabletimer () function is called, the timer is triggered every 5 seconds.
You can also set the timer to periodic self-excitation.
Sends a cycle parameter (in milliseconds) to the third parameter of setwaitabletimer ). In the second part of createwaitabletimer ()
Parameters pass false to generate a timer for auto-return. 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. The following conditions are met: An entity is added to the APC queue, timeout, activation handle, and so on.
When msgwaitformultipleobjectsex () is called, a message enters a message queue of the thread. If the waiting condition meets an actual condition in the APC queue
The thread is activated and the complete routine is executed. 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
If the APC queue is faster than the processing speed, the call to these functions may never return. 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, and
No entity is added 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. On the timer
When an entity is added to the APC queue of this thread, sleep () will wake up the 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", pmydata-> sztext,
Pmydata-> dwvalue );
Messagebeep (0 );

}

Void main (void)
{
Handle htimer;
Bool bsuccess;
_ Int64 qwduetime;
Large_integer liduetime;
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 & 0 xffffffff );
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 susponded 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.