Windows Phone development (11): Overview and example of scheduled tasks periodictask and resourceintensivetask

Source: Internet
Author: User

As mentioned above,

Scheduled tasks allow applications to execute the background agent on condition that the master program is not activated. Unlike scheduled notification, scheduled tasks can only be executed in two types: periodictask and resourceintensivetask.

Periodictask is periodically executed, but the execution time is short, and the processing cycle, memory, and other system resources are restricted. This type is suitable for fast tasks, such as checking the number of Web services that enable the location function, or buffering a small amount of data.

Resourceintensivetask is occasionally executed when the device is in a state of abundant resources. For example, the device is in a Wi-Fi network connection and the device is powered by an external power supply. This type of task can run for a longer period of time to process a large amount of data when sufficient device resources are allowed, that is, the execution time of this type of task is flexible.

The following is an excerpt from msdn .,

 

 

Both scheduled tasks and background proxies allow applications to execute code in the background, even if the application is not running in the foreground. Different types of scheduled tasks are designed for different types of background processing solutions, so they have different behaviors and restrictions. This topic describes the plan, duration, and limits of scheduled tasks.

 

Types of scheduled tasks

The following lists the types of scheduled tasks. Note that scheduledtask is derived from scheduledaction. The code running in the background is placed in the class derived from scheduledtaskagent (derived from backgroundagent.

 

Scheduled Task Type

Description

Periodictask

The regular proxy runs for a short period of time at regular repetition intervals. A typical scenario for this type of task includes the location of the upload device and the execution of a small amount of data synchronization.

Resourceintensivetask

The resource-intensive Agent runs when the mobile phone meets a set of requirements related to processor activity, power supply, and network connection, and runs for a relatively long time. A typical solution for this type of task is to synchronize a large amount of data to the mobile phone when the user does not take the initiative to use the mobile phone.

 

Background proxy Lifecycle

An application may have only one background proxy. You can register the proxy as periodictask, resourceintensivetask, or both. The schedule for running the agent depends on the registered Task Type. The details of the plan will be described later in this topic. Only one proxy instance can be run at a time.

The proxy code is implemented by the application in the class inherited from the backgroundagent. The operating system calls oninvoke (scheduledtask) when the agent starts ). In this method, the application can determine which scheduledtask type it runs and perform corresponding operations. After the agent completes its task, it should call yycomplete () or abort () to let the operating system know that it has completed. If the task is successful, use yycomplete. If the agent cannot execute its tasks (if the required server is unavailable), the agent should call abort, which will cause the isscheduled attribute to be set to false. The foreground application can check this attribute during its running to determine whether abort is called.

 

Restrictions on all scheduled task types

The following restrictions apply to all scheduled tasks.

 

Restrictions

Description

Unsupported API

There is a group of APIs that cannot be used by any scheduled task. Using these Apis will cause exceptions at run time, or cause applications to fail to authenticate when they are submitted to the Windows Phone marketplace. For a list of restricted APIs, see APIs not supported by the background proxy of Windows Phone.

Maximum memory usage

Regular proxy and resource-intensive Code cannot use more than 6 MB of memory at any time. The audio proxy is limited to 15 MB. If the scheduled task exceeds the upper limit of memory, it is terminated immediately.

Pause the memory and time-out limits when running in the debugger. You can use the applicationmemoryusagelimit API to query the memory limits of foreground applications and background proxies.

Re-plan every two weeks

Use the expirationtime attribute of the scheduledtask object to set the time when the task is no longer running. When you use the add (scheduledaction) method to schedule an operation, this value must be set to a time within two weeks. When the application associated with the task runs on the foreground, the task may be rescheduled and the expiration time is reset to a maximum of two weeks from the current time.

Cancel the proxy plan after two successive crashes

If you exit two times in a row because the memory quota is exceeded or any other unhandled exceptions occur, the scheduled proxy and resource-intensive proxy are canceled. The proxy must be rescheduled by the foreground application.

 

Restrictions on regular proxy

The following are the plans, durations, and general limits of regular agents.

 

Restrictions

Description

Scheduled interval: 30 minutes

The regular proxy usually runs every 30 minutes. To optimize the battery time, the scheduled agent can run in the same way as other background processes. Therefore, the execution time may be at most 10 minutes away.

Planned duration: 25 seconds

Regular proxy usually runs for 25 seconds. Other restrictions may cause termination of proxy extraction.

The power-saving mode may block execution.

Power-saving mode is an option. You can enable this option on the device to indicate that the battery time should be prioritized. If this mode is enabled, the regular proxy may not run, even if the interval has elapsed.

Periodic proxy restrictions for each device

To help maximize the battery usage time of the device, the number of scheduled agents on the opponent's machine is limited. It varies with the configuration of each device and can be as low as 6. There is another restriction that is lower than the hard limit. If the limit is exceeded, the user will be warned that they are running multiple background proxies, so the battery consumption may be faster.

Warning:If you try to add a regular background proxy when the device limit is exceeded, calling add (scheduledaction) will cause invalidoperationexception. Because the regular proxy limit for each device is very low, your application may encounter this exception. For this reason, it is important that you capture this exception when adding a scheduled proxy so that your application will not crash. The sample code can be found in the background proxy best practices of Windows Phone.

 

Resource-intensive proxy restrictions

The following are the plans, durations, and general limits of resource-intensive agents.

 

Restrictions

Description

Duration: 10 minutes

The resource-intensive agent usually runs for 10 minutes. Other restrictions may cause termination of proxy extraction.

External Power supply required

The resource-intensive agent does not run unless the device is connected to an external power supply.

Non-mobile network connection required

The resource-intensive agent does not run unless the device establishes a network connection through a Wi-Fi or PC connection.

Minimum battery power

The resource-intensive agent does not run unless the battery power of the device is higher than 90%.

Device screen lock required

The resource-intensive agent does not run unless the device screen is locked.

Inactive mobile phone call

When a mobile phone call is active, the resource-intensive agent does not run.

You cannot change the network to a mobile phone network.

If the resource-intensive proxy attempts to call the associatetonetworkinterface (socket, networkinterfaceinfo) of the associlebroadbandgsm () or mobilebroadbandcdma (), the method fails to be called.

If the device reaches a State where all required conditions are met and a resource-intensive proxy is enabled, when the device status changes so that it does not meet any conditions, the resource-intensive proxy is terminated immediately.

Bytes ------------------------------------------------------------------------------------------------------

In wondwos phone 7.1, a method is provided to execute multiple Work Plan tasks. We can define a work content and submit it to the job system for execution, however, not all work can be performed due to resource restrictions on mobile phones. Windows Phone 7.1 supports two tasks that can be scheduled in the background:

1. periodictask

2. resourceintensivetask

Both methods have the following requirements:

Periodictask:

Execution time: every 30 minutes, with an error of about 10 minutes

Maximum memory usage: less than 6 MB

Executable time: 25 seconds.

Power-saving mode may not be executed

Maximum number of executable tasks: 6.

 

 

Resourceintensivetask:

Maximum memory usage: less than 6 MB

Executable time: 10 minutes.

Execution conditions: the external power supply, Wi-Fi or direct connection to the computer, battery power must be greater than 90%, the screen cannot be locked, and the status of the phone is not answered.

Each application can set up to one periodictask and resourceintensivetask. The expiration time of a job (expirationtime) must be within two weeks, and some APIs cannot be used, to schedule a job, you must start the schedule when the user executes the application for the first time. There are many restrictions on the usage.

 

 

 

Example 1:

 

It is quite simple to create a scheduled task. First, create a basic Windows Phone app, then create a project for the scheduled task, and the app references the scheduled task.

.

  

Next, put a button in the app to start the job schedule:

  

Private void btnstart_click (Object sender, routedeventargs e) {periodictask task = (periodictask) scheduledactionservice. find ("taskagent"); If (task = NULL) {task = new periodictask ("taskagent"); task. description = "";} else {// If (! Task. isscheduled) {string lastresult; If (isolatedstoragesettings. applicationsettings. trygetvalue <string> ("taskresult", out lastresult) {If (lastresult = "succes") {MessageBox. show ("user-related scheduling"); scheduledactionservice. remove (task. name); return;} else if (lastresult = "faillure") {}} scheduledactionservice. remove (task. name);} // task expiration time. expirationtime = datetime. now. adddays (14); try {SC Heduledactionservice. add (task); # If debug_agent scheduledactionservice. launchfortest (task. name, timespan. fromseconds (60); # endif} catch (invalidoperationexception) {MessageBox. show ("the maximum number of scheduled Rows has been reached or the user has stopped the function. ");} Catch (schedulerserviceexception SSE) {MessageBox. Show (SSE. Message );}}

 

 

Before adding a job to a schedule, remember to judge whether there is a overlap. If there is already a schedule, you need to determine the status of the current schedule. If you need to reschedule the schedule, remove the current schedule and then add it again.

In addition, scheduledactionservice. launchfortest can be used for quick execution during the test (otherwise, it will take about 30 minutes to complete at least !)

Protected override void oninvoke (scheduledtask task)
{
If (task is periodictask)
{
// Logic for periodic task
}
Else
{
// Logic for resourceintensivetask
}
// Use this to invoke your task much quicker when debugging
# If debug_agent
Scheduledactionservice. launchfortest (task. Name, timespan. fromseconds (60 ));
# Endif
// Tell the scheduler we are done
Notifycomplete ();
}

 

Related Article

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.