Enterprise Networks & Servers
Search
 
More articles
Industry news
A Second Look

Resources
Contact us

 
October 2004 issue
Features 
leather so soft lyrics Buy Cheap Software - Discount Software graphs charts microsoft prices buy soft software prices

Programmatically Waking a Windows PC from Suspension

As computers take on more and more automated tasks, they seem to spend more and more time fully powered on. In many cases personal computers are left running 24 hours a day just to accommodate certain tasks that the computer may do during non-working hours.

For example, a disk utility may be set to defrag the hard disk during the middle of the night, or as we move into the era of the digital home, a computer may be left running so that the PVR software can record the user's favorite television show.

Mobile systems, however, have limited power resources. It would be unwise to leave a laptop powered on when not being used and running on batteries, just to perform a task in the middle of the night. Allowing a mobile system to go into suspension and then waking it as needed is a much smarter option. Certainly there are tasks that require the computer to be always on, for example acting as a Web server, but for other tasks there is often a better method.

Microsoft Windows and other operating systems have long had the ability to automatically put the computer into a suspension mode after a period of inactivity. This mode turns off certain parts of the computer and only uses a small amount of power to maintain the current memory state. While ideal for saving power, it does cause a problem for any scheduled tasks that may have to be performed by the computer. This document will cover both the technique of scheduling a Windows based computer to wake up from sleep mode to perform a task, as well as preventing the computer from transitioning to sleep mode during the task.

Let's pause a second and examine what it means for a computer to suspend. Modern computers have many different power states as defined by ACPI (Advanced Configuration and Power Interface), an industry standard interface for power management. These states are labeled S0 through S5 and are summed up below.

S0 — Computer in running state
S1 — Computer in sleep state
S2 — Computer in sleep state
S3 — Computer in sleep state
S4 — Computer in hibernation
S5 — Computer off

Different levels of sleep save varying amounts of power, but deeper sleep states require longer for the computer to resume.

For this discussion we will focus on two general forms of suspension: sleeping or "stand-by" and hibernation. It is important to understand the key differences between the two.

Stand-by causes the system to shut down many non-vital components like the hard disk and the display. But it continues to keep power running to the DRAM in the system, thus maintaining any running applications and their data. This allows a very fast resume when the user pushes a key on the keyboard, moves the mouse, or presses the power button on the front of the case. But if the power goes out while in this state, the state of DRAM will be lost and any unsaved data with it.

Hibernation takes the contents of the DRAM and writes it directly to a special file on disk. It then proceeds to shut the entire system down, including the DRAM. Upon resume, the system reads the contents of hibernation file and places it back into memory. Resume is not quite as fast as stand-by, but hibernation uses less power and is less prone to failure if the power goes out. In hibernation, the system appears to the user to be completely powered off.

Typically, a computer is set up to go into the stand-by state after some specified amount of inactivity, and then to transition into hibernation after an additional amount of time. This is completely up to the user to configure.

It is important to note that the methods shown in this document allow the system to wake from either the stand-by state or the hibernation state, and the application doesn't really have to worry about which state it was in.

To illustrate automatically waking up a computer, it is helpful to establish a simple scenario using an imaginary Personal Video Recorder (PVR) application. Our PVR is set up to record our favorite shows, including our most favorite, infomercials. Since the very best infomercials air during the middle of the night we have to rely on our computer being able to record unassisted. Of course an easy way to make sure our computer is ready to go at 1:00 in the morning is to turn off all power management features and allow the computer to run all the time. But this would not be environmentally responsible and we could do without the extra heat generated by our computer during the summer months.

Since the little environmentalist in us has decided to allow our computer to sleep when we are not using it, let's see how this affects the PVR. We have set our computer to go to sleep after 30 minutes of inactivity. If no mouse movement or keyboard input is detected for that amount of time, and no other application informs the operating system (OS) to not go to sleep, the computer will transition to the sleep state. Of course during the day we actively use the computer, either typing some e-mail, browsing to a Web site or even watching a recorded show so it doesn't sleep during this active time. The PVR is able to record television in the background at the same time we are actively using the computer. But after we go to bed at 9:00, the computer also goes to sleep, after the required 30 minutes, at 9:30. At 1:00 as our favorite infomercial is airing, the system is still asleep and the PVR is unable to record the show.

To solve the dilemma, we will integrate some simple code into the PVR app to allow the computer to not only go to sleep when no activity is scheduled, but also to wake the system back up when our favorite infomercial is about to air.

How to Wake Back Up

To schedule the system to wake up, we will use an object known as a waitable timer. Waitable timer objects are synchronization objects that become signaled at a scheduled time. Window's task scheduler uses these as wake events that inform it to resume from a sleeping state to run a certain application, like disk defragmentation. An application can also use these objects to wake the system for purposes such as our imaginary PVR.

Since the application can't know when the system might be asleep, it should use a waitable timer for every scheduled event. Thus it will always wake up the system if asleep, and if not asleep, does no harm.

For example, in the PVR application a waitable timer would be set for the next upcoming recorded show, and then, once a show is recorded, set again for the next show, and so forth. This guarantees that if the system goes into a suspend state at any point between two scheduled recording sessions the system will awaken for the next scheduled recording.

First the application makes a call to CreateWaitableTimer to create the waitable timer object. Next it uses the SetWaitableTimer to schedule when it wants the timer object to become signaled and thus wake up the computer if it is asleep. For our PVR we will assume some data that indicates what time to start and stop recording.

In real PVRs this data is usually kept in some sort of database, but we will ignore all this complexity for our app and just have a hard-coded time. The code below shows this.

GetLocalTime(&sTimeCurrent);
sTimeRecord = sTimeCurrent;
sTimeRecord.wMinute += 1; //Set the timer to go off 1 minute from current time
//Convert to a FILETIME
SystemTimeToFileTime(&sTimeRecord,&fLocalTime);

//Convert from local time to UTC time since the system works on UTC internally.
LocalFileTimeToFileTime(&fLocalTime,&fTime);

//Put time into a LARGE_INTEGER structure for the SetWaitableTimer function
liDueTime.HighPart = fTime.dwHighDateTime;
liDueTime.LowPart = fTime.dwLowDateTime;

//Create the WaitableTimer
hTimer = CreateWaitableTimer(NULL,TRUE,NULL);

//Set the timer with the required time
//Set the last parameter to true to wake up the computer if asleep
SetWaitableTimer(hTimer,&liDueTime, 0, NULL, NULL, TRUE);

After the computer has been restored from suspension the application can do its work. But without user input the system will try to re-enter suspension after an elapsed period of time. This of course would be very bad if the required work is not finished. For example, our PVR application may be recording the user's favorite television program, which lasts for an hour. If the system were to re-enter suspension at any time during this hour the user would be quite upset they missed parts of the show.

To overcome this limitation, Windows provides the SetThreadExecutionState function to allow an application to notify the system that it is currently busy and to not suspend the computer. For example the code below will inform the system to remain powered on until another call to SetThreadExecutionState is made.

etThreadExecutionState(ES_SYSTEM_REQUIRED | ES_CONTINUOUS);

This function can be used with a combination of three flags which are summarized below.

ES_SYSTEM_REQUIRED: Keeps the system awake but will allow the display to be powered down.

ES_DISPLAY_REQUIRED: Keeps both the system and the display powered up.

ES_CONTINUOUS: Used in conjunction with above flags or by itself to indicate that the given state should remain in effect until another call the SetThreadExecutionState occurs.

Of course this ability comes with some warnings. If used improperly this would allow an application to keep the entire system from entering suspension even if nothing important is going on at the time. So it is important to remember to utilize this feature only when critical work is required.

Understanding when to use this functionality is important. The previous example showed that it would be desirable to prevent suspension for the duration of a scheduled recording, but should allow the system to re-suspend after the recording is done. Another example of when to use this would be as the user watches a show. It would be very annoying to have the system suspend during the climax of a movie.

Furthermore an application that wakes the system should not prevent the system from suspending while waiting for user input. It may be a long time before the user returns to give that input, and during that time the system could have suspended to save power.

Tips and Tricks/Caveats

It is obvious that care must be taken to plan out how an application will implement some of these functions. Many use cases should be considered before implementing a good system that will maximize functionality, usability and power savings. Many applications will not need to worry about restoring a computer from suspension where others will need to consider it as basic functionality.

One problem that an application does need to consider is that it may take some time to recover from suspension before being able to process. For example if a computer is in a stand-by mode the system may recover very quickly and be available to the application for processing. But if restoring from a hibernation mode the system may take several seconds or even minutes to restore. Thus if an application knows that it must start processing at a scheduled time it should actually schedule the system to wake up a few minutes beforehand.

An application should also be aware that it may miss a scheduled restore. For example if the user hibernates the system but then unplugs the system or there is a power outage, it is possible that a scheduled restore would be missed and the application would not be able to do its work at that time. Thus even after the system is restored the application should recheck the date and time and adjust itself appropriately. An example of this would be our PVR application missing a scheduled recording due to the above scenario. The next time the system is restored the application should check to see what it has missed and perhaps create a prompt for the user notifying them of the problem, then reprocess the upcoming schedule and get ready to set waitabletimers for each of them.

As computers continue to perform more and more automated tasks, they also tend stay in a fully powered on state continually. Users simply don't want to have to worry about turning on the computer at the proper time.

Utilizing techniques outlined in the document above allow the application to wake the computer only when needed. This saves power and reduces noise and heat generated from a running computer.

The following documents provide valuable context to the discussion in this article.

Microsoft MSDN: http://msdn.microsoft.com for more info on power management in the Windows environment.

Intel provides an array of value-added products and information to software developers.

The Early Access Program: www.intel.com/ ids/ eap provides software vendors with Intel's latest technologies, helping member companies to improve product lines and grow market share.

Intel Developer Services: www.intel.com/ ids offers free articles and training to help software developers maximize code performance and minimize time and effort.

Intel Software Development Products: www.intel.com/ software/ products includes compilers, performance analyzers, performance libraries and threading tools.

Intel Solution Services: www.intel.com/ internetservices/ intelsolutionservices is a worldwide consulting organization that helps solution providers, solution developers, and end customers develop cost-effective e-Business solutions to complex business problems.

ITIntel: www.intel.com/ ebusiness/ it/, through a series of white papers, case studies, and other materials, describes the lessons it has learned in identifying, evaluating, and deploying new technologies.

The Intel Software College: www.intel.com/ software/ college/ provides a one-stop shop at Intel for training developers on leading-edge software-development technologies. Training consists of online and instructor-led courses covering all Intel architectures, platforms, tools, and technologies.

Blake Thompson is a senior software engineer at Intel Corp. His duties include working with third party software companies to optimize and enable their applications. He is currently focusing on digital home and mobile applications.

 
This article appears in the October 2004 issue of Enterprise Networks & Servers.

 Other articles in this section 
 

Publications & Communications Inc.

 

Email Address:
 
 

Copyright ©2003-2010 by Publications & Communications Inc. (PCI)
All rights reserved. Reproduction without written consent is prohibited.

HomeContact usSubscriptions