Jerry Nixon @Work: Windows 8: Scheduled Tasks & the Lock Screen

Jerry Nixon on Windows

Friday, August 31, 2012

Windows 8: Scheduled Tasks & the Lock Screen

imageWindows 8 apps are like a stack of cards. Only the top card is active – the rest (apps) have their threads suspended. Windows 8 snap view actually allows for two active apps. That’s pretty cool.

Here’s what you need to know:

Background tasks

Some developers need to run code when apps are not running. For this, there is the background task. These are periodic and have constrained CPU and Network usage.

There are two types of background tasks: standard and lock screen tasks. There can be only 7 lock screen tasks, and the key difference is the constraint thresholds.

CPU quota

The first type of quota is CPU time; this is not clock time. It dramatically impacts battery life. However, this CPU quota is enforced on battery and on AC power.

Every two hours a standard task is granted 1 CPU second to complete its work. If it fails to finish, it is suspended until more time is given. Lock screen tasks are granted 2 CPU seconds every 15 minutes.

MSDN: An app on the lock screen receives a certain amount of CPU time at regular intervals for its background tasks. If the app uses all of its available CPU time, its background tasks are suspended until the app’s CPU quota is replenished at the next generation for CPU quota updates.

Network quota

The second type of quota is Network bandwidth. Like CPU time, network consumption dramatically impacts battery life. However, Network quotas are only enforced when on battery.

First, quota amounts vary by bandwidth. Assuming 10Mbps, lock screens get 45 MB a day. Standard background tasks only get 7.5 MB a day.

More than one

A Windows 8 app can easily have than one background task. However, all Windows 8 app background tasks split the quotas of CPU and network bandwidth.

Custom code

Push notifications handle background tile updates for apps. The playback manager handles background audio for apps. The background transfer API handles downloading and uploading for apps. Share contracts handle sharing code between apps. And, background tasks can execute custom code.

Phone home

Not so long ago SETI began its sweep of the heavens. The resulting tidal wave of data needed to be processed to look for patterns in the night sky. To accomplish this, volunteers installed the SETI screensaver to process blocks of data while the user was away. It was brilliant.

This is an example of a terrible use of Windows 8 background tasks. Not only are Windows 8 background tasks limited in their network traffic, but with just 1 or 2 CPU seconds, the amount of processing is constrained to prevent heavy processor / battery consumption.

Lock screen

So, you wanna be a lock screen task? You need to remember one thing. The user is in charge. You can programmatically add your app to the lock screen. But the user can snap you back so hard you’ll think you’re a first year cadet again. So don’t get too high and mighty.

MSDN: An app can register to be notified when it is added or removed from the lock screen by registering a background task with the LockScreenApplicationAdded or LockScreenApplicationRemoved triggers provided in the SystemTrigger class.

Self-promotion

Oh, yes you can! An app can programmatically add itself to the lock screen by using the BackgroundExecutionManager class – something like “await BackgroundExecutionManager.RequestAccessAsync()”. But don’t be slippery about it; this type of code needs to be in a button click handler (or some user-induced event handler).

Sharing data

The UI app might have something the background app needs. Then again. The background app might want to hand something to the UI app. The best and most reliable approach is to use persistent storage – such as the isolated folders that the tasks and UI apps share in common.

Note: No matter what, do NOT communicate directly. It’s nothing but trouble!

Trigger me this

It is necessary for a task to be based on exactly one trigger. These are the causes for the task to be invoked. And here’s the list: ControlChannelTrigger, MaintenanceTrigger, PushNotificationTrigger, InternetAvailable, LockScreenApplicationAdded, LockScreenApplicationRemoved, ControlChannelReset, NetworkStateChange, OnlineIdConnectedStateChange, ServicingComplete, SessionConnected, SessionDisconnected, SmsReceived, TimeZoneChange, UserAway, UserPresent, TimeTrigger

Similar to triggers are conditions. A task may include zero or more conditions to filter its execution. And here’s the list: InternetAvailable, InternetNotAvailable, SessionConnected, SessionDisconnected, UserNotPresent, UserPresent.

If your task is based on the TimeTrigger then you might only want to execute when InternetAvailable. That makes sense. Combining the condition with the trigger removes the need to spin up your task or for your task to reach out and test for the condition.

Not for everyone

But wait, the gulf between the top 1% and the rest of us is getting wider. Not all triggers and not all triggers and conditions are available to standard tasks. Here’s the list of lock screen only triggers: TimeTrigger, PushNotificationTrigger, ControlChannelTrigger. And, here’s the list of lock screen only conditions: SessionConnected, UserPresent, UserAway and ControlChannelReset.

Latching on?

An important concept is latching. This is where the trigger occurs (like, time) but the condition is false. In this case, the trigger is latched (so to speak). At the moment when the condition is met, it is not required that the trigger fire again – the trigger is raised and the task is executed immediately.

Cancel

At any point for execution and for a million reasons (such as Connected Standby), the operating system can request that a task cancel. That gives you 5 seconds to comply. If you do, then it is happiness. If you do not, then the OS will forcibly terminate your task.

Windows Phone

Like so many things in Windows 8, if you are a Windows Phone developer you have a tremendous head start in understanding the lifecycle and background task architecture of Windows 8. It’s amazingly similar. Registering your task is almost identical – use BackgroundTaskBuilder.

Like Windows Phone, tasks are class libraries (marked as WinMD) implementing IBackgroundTask’s Run() method where all the work takes place. It’s really that easy. Here are some serious resources to get you started.

Best of luck!