使用维护触发器Use a maintenance trigger

重要的 APIImportant APIs

了解如何使用 MaintenanceTrigger 类在设备接通电源时在后台运行轻型代码。Learn how to use the MaintenanceTrigger class to run lightweight code in the background while the device is plugged in.

创建一个维护触发器对象Create a maintenance trigger object

本示例假定在插入设备时你已具有可以在后台运行的轻型代码以增强你的应用。This example assumes that you have lightweight code you can run in the background to enhance your app while the device is plugged in. 此主题重点介绍 MaintenanceTrigger,它类似于 SystemTriggerThis topic focuses on the MaintenanceTrigger, which is similar to SystemTrigger.

有关编写后台任务类的详细信息可以在创建和注册进程内后台任务创建和注册进程外后台任务中找到。More information on writing a background task class is available in Create and register an in-process background task or Create and register an out-of-process background task.

创建新的 MaintenanceTrigger 对象。Create a new MaintenanceTrigger object. 第二个参数 OneShot 指定维护任务是只运行一次还是继续定期运行。The second parameter, OneShot, specifies whether the maintenance task will run only once or continue to run periodically. 如果 OneShot 设置为 true,则第一个参数 (FreshnessTime) 会指定在计划后台任务之前需等待的分钟数。If OneShot is set to true, the first parameter (FreshnessTime) specifies the number of minutes to wait before scheduling the background task. 如果 OneShot 设置为 false,则 FreshnessTime 会指定后台任务运行的频率。If OneShot is set to false, FreshnessTime specifies how often the background task will run.

备注

如果 FreshnessTime 设置为不到15分钟,则在尝试注册后台任务时会引发异常。If FreshnessTime is set to less than 15 minutes, an exception is thrown when attempting to register the background task.

此代码示例创建一个触发器,该触发器每小时运行一次。This example code creates a trigger that runs once an hour.

uint waitIntervalMinutes = 60;
MaintenanceTrigger taskTrigger = new MaintenanceTrigger(waitIntervalMinutes, false);
uint32_t waitIntervalMinutes{ 60 };
Windows::ApplicationModel::Background::MaintenanceTrigger taskTrigger{ waitIntervalMinutes, false };
unsigned int waitIntervalMinutes = 60;
MaintenanceTrigger ^ taskTrigger = ref new MaintenanceTrigger(waitIntervalMinutes, false);

(可选)添加条件(Optional) Add a condition

  • 如果需要,创建一个后台任务条件以控制任务何时运行。If necessary, create a background task condition to control when the task runs. 防止后台任务在未满足条件之前运行的条件,有关详细信息,请参阅设置运行后台任务的条件A condition prevents your background task from running until the condition is met - for more information, see Set conditions for running a background task

在该示例中,条件设置为 InternetAvailable 以便在 Internet 可用时(或者变为可用时)运行维护。In this example, the condition is set to InternetAvailable so that maintenance runs when the Internet is available (or when it becomes available). 有关可能的后台任务条件列表,请参阅 SystemConditionTypeFor a list of possible background task conditions, see SystemConditionType.

以下代码向维护任务生成器中添加一个条件:The following code adds a condition to the maintenance task builder:

SystemCondition exampleCondition = new SystemCondition(SystemConditionType.InternetAvailable);
Windows::ApplicationModel::Background::SystemCondition exampleCondition{
    Windows::ApplicationModel::Background::SystemConditionType::InternetAvailable };
SystemCondition ^ exampleCondition = ref new SystemCondition(SystemConditionType::InternetAvailable);

注册后台任务Register the background task

  • 通过调用后台任务注册函数注册后台任务。Register the background task by calling your background task registration function. 有关注册后台任务的详细信息,请参阅注册后台任务For more information on registering background tasks, see Register a background task.

以下代码将注册维护任务。The following code registers the maintenance task. 请注意,假设后台任务将在独立于应用的进程中运行,因为它指定 entryPointNote that it assumes your background task runs in a separate process from your app because it specifies entryPoint. 如果后台任务将在应用的同一个进程中运行,不要指定 entryPointIf your background task runs in the same process as your app, you do not specify entryPoint.

string entryPoint = "Tasks.ExampleBackgroundTaskClass";
string taskName   = "Maintenance background task example";

BackgroundTaskRegistration task = RegisterBackgroundTask(entryPoint, taskName, taskTrigger, exampleCondition);
std::wstring entryPoint{ L"Tasks.ExampleBackgroundTaskClass" };
std::wstring taskName{ L"Maintenance background task example" };

Windows::ApplicationModel::Background::BackgroundTaskRegistration task{
    RegisterBackgroundTask(entryPoint, taskName, taskTrigger, exampleCondition) };
String ^ entryPoint = "Tasks.ExampleBackgroundTaskClass";
String ^ taskName   = "Maintenance background task example";

BackgroundTaskRegistration ^ task = RegisterBackgroundTask(entryPoint, taskName, taskTrigger, exampleCondition);

备注

对于除台式机以外的所有设备系列,如果设备内存不足,后台任务可能会终止。For all device families except desktop, if the device becomes low on memory, background tasks may be terminated. 如果没有呈现内存不足异常,或者应用没有处理该异常,则后台任务将在没有警告且不引发 OnCanceled 事件的情况下终止。If an out of memory exception is not surfaced, or the app does not handle it, then the background task will be terminated without warning and without raising the OnCanceled event. 这有助于确保前台中应用的用户体验。This helps to ensure the user experience of the app in the foreground. 应该将后台任务设计为处理此情形。Your background task should be designed to handle this scenario.

备注

通用 Windows 平台应用必须先调用 RequestAccessAsync ,然后才能注册任何后台触发器类型。Universal Windows Platform apps must call RequestAccessAsync before registering any of the background trigger types.

若要确保通用 Windows 应用在你发布应用的更新后继续正常运行,则必须在启动已经过更新的应用时调用 RemoveAccess,然后调用 RequestAccessAsyncTo ensure that your Universal Windows app continues to run properly after you release an update to your app, you must call RemoveAccess and then call RequestAccessAsync when your app launches after being updated. 有关详细信息,请参阅后台任务指南For more information, see Guidelines for background tasks.

备注

后台任务注册参数在注册时验证。Background task registration parameters are validated at the time of registration. 如果有任何注册参数无效,则会返回一个错误。An error is returned if any of the registration parameters are invalid. 确保你的应用能够流畅地处理后台任务注册失败的情况,否则,如果你的应用依赖于在尝试注册任务后具备有效注册对象,则它可能会崩溃。Ensure that your app gracefully handles scenarios where background task registration fails - if instead your app depends on having a valid registration object after attempting to register a task, it may crash.