Windows Phone development (12): Summary and example of the scheduled task background Schedule Tasks

Source: Internet
Author: User
Tags soap client

In wp7.1, the new API for the background agent adds many very powerful parts. The following section describes the scheduled multi tasking part.

Scheduled multi tasking mainly enables the application to support tasks in Multi-job mode, so that the application can continue to execute some specific tasks in the background, for example: download background, update background information, and call background services... .

However, wp7.1 provides the Agent Mode to allow the logic to be executed in the background during application development to be placed independently in the agent to complete tasks through scheduling.

However, the agent and application must belong to different projects, because isolatedstoragesettings in isolatedstorage cannot be shared. to exchange information, you must use isolatedstorage files or other methods.

Therefore, when designing an application that supports the background agent (scheduledtaskagent), I have several considerations:

1. Separate the background execution logic into a category or module, which completes all background tasks;

2. Use the config file to separate the parameters or execution results from the file. Both the application and agent can be obtained;

3. The agent is a background task, and the fault tolerance mechanism in case of exceptions in the background needs to be specially designed. Users should be notified through notice as much as possible;

Next, we will discuss in detail that scueduled tasking is composed of important elements:

> Microsoft. Phone. scheduler-scheduled multi tasking:

Wp7.1 allows Schedule Tasks and background agent to execute their tasks in the background. However, Schedule Tasks and background agent are used differently:

‧ Schedule task: the focus is to specify the "phase/delay" to execute the task, and re-execute the task by setting the time frequency of schedule;

‧ Background agent: the priorities of different agents can be subdivided, but tasks triggered by one-time tasks or external events are compared;

Microsoft. Phone. schecloud provides the use of task and notification for scheulde. Schedule task is another use. Schedule notification is described in another article <>.

However, the usage of scheulde tasks involves several important elements that must be understood. The following describes in detail:

A. scheduledactionservice:

Dedicated to managing all scheduled actions for this device. Scheduled Actions includes the alarm and reminder that can be used for notifications. It also includes the following two periodic tasks running on the background agent and resource-intensive tasks. The important method is as follows:

Name Description
Add Send a scheduled action to the job system. It uses the name of scheduled action as the recognition value.
Find Find the scheduled action by using a specific name.
Getactions (of T) Return all specified types of Scheduled Actions in the system.
Launchfortest After a specified delay time and scheduledtask are specified, the background agent is required to execute the scheduledtask.
Remove Remove the specified scheduled action from the scheduled Action Service.
Replace It usually works with find to find the scheduled action of the specified name and replace it.

 

B. periodictask:

Periodic (periodic) task is a concept of regular agency operation. It takes less time to operate tasks in a background and is a regular period of execution in the execution compartment.

Common scenarios, such as regularly uploading location information of mobile phones, synchronizing a small amount of data, and updating the tile status... .

B-1. Use of periodic task constraints and time period recommendations

Constraints/suggestions Description
Schedule interval: 30 minutes It is usually executed every 30 minutes. When the power condition is good, it can be used with other background processes, or set to be close to the upper or lower gap for 10 seconds.
Schedule duration Generally, it can be executed for 25 seconds, but the agent may be terminated early due to other reasons.
Exception can be prevented when the battery is saved. Whether or not the battery is to use the saving mode is selected by the user. If this mode is selected, the periodic task may be unavailable when the battery enters the Save mode.
Restrictions of each device on the periodic task In order to maximize the battery usage, different devices have certain limits on battery usage. Therefore, a maximum of several agents can be executed on a device. If the limit is exceeded, it is automatically turned off.

 

C. resourceintensivetask:

Resource-intensive (resource-intensive) tasks are applicable to scenarios that require a relatively long processing time or a large amount of Mobile Phone Power, network, and other resources.

Common use cases, such as synchronizing a large amount of data (for example, the app needs to download a large amount of data to the mobile terminal to allow the app to run )... .

C-1. Constraints and time period recommendations using resourceintensivetask

Constraints/suggestions Description
Duration: 10 minutes Generally, the execution of the resource-intensive agent lasts for about 10 minutes. If there are other restrictions, the execution of the agent will be stopped early.
External Power Demand It cannot be executed unless the device is connected to an external power source.
No mobile network capability The device cannot be executed unless it has been connected to a PC through Wi-Fi, mobile network, or.
Minimum power demand Resource-intensive agent cannot be executed unless the power usage exceeds 90%..
The device screen is locked. The resource-intensive agent cannot be executed unless the phone is locked..
Call unavailable The resource-intensive agent cannot be used when the mobile phone is in the active state.
Cannot change the network status to Mobile Network If the resource-intensive agent attempts to invoke associatetonetworkinterface (socket, networkinterfaceinfo) to specify any type of mobile network (GSM or CDMA), it will fail.

 

These two elements are actually implemented by the scheduleaction and scheduledtask abstract categories. They have their own use situations and applicability, respectively,

The biggest difference between the two lies in the use of the situation and the amount of mobile phone resources required, and the resource-intensive task must be locked on the screen and more than 90% of the power.

Resource-intensive tasks require many restrictions. Therefore, you must consider this part when designing scheduled tasks.

Attributes are similar. The following describes the attributes that have been used for a long time:

Name Description
Description Set/get the description about the scheduled task. The content of this description will appear on the "Settings/applications/background tasks Settings" page.
For example, the program name is background scheulde:
Expirationtime Set/get the expiration time of scheduled task.
Isscheduled Obtain whether the scheduled task status is started.
Lastexitreason Obtain the reason why the last task executed by the agent is terminated.
Lastscheduledtime Obtains the time when the Agent executes the most recent task, mainly based on the mobile phone time.
Name Obtain the name of the scheduled action.

 

After learning the basic attributes and usage situations of the two elements, pay special attention to the following when using the background agent:

1. One application can only have one background agent (scheduledtaskagent), but the agent can use periodictask, resourceintensivetask separately.

Or use both. Note that one agent can only have one periodictask and one resourceintensivetask.

2. Background agent (scheduledtaskagent ):

2-1. The part that triggers the agent logic through oninvoke (scheduletask;

2-2. When you have successfully executed all the tasks, remember to call yycomplete () to inform the agent that the task has been completed;

2-3. If an error occurs during execution or the task cannot be executed, remember to notify the agent to cancel the operation. However, you can obtain

The isscheduled attribute in scheduledtask is false. But remember to use shelltoast to inform the user of How to abort (), so that the user does not know.

3. Control the memory usage of the background agent:

3-1. Periodic agents and resource-intensive agents allow up to 6 MB memory usage for each task execution.

3-2. Audio agents limits the memory usage to 15 MB.

3-3. In debug mode, there is no limit, but you can use the API to query the situation of using bucket memories in each part.

4. reschedule scheduled after the default agent is two weeks:

Although the lastscheduledtime in scheduledtask can be used to determine what the datetime was last executed, and expirationtime can be used to specify the task

The length of time that can be run. However, the use of scheduledtask may be caused by restrictions (for example, when the task is executed without the network capability, the agent is automatically required to be postponed ).

The task is not executed for a long time. To ensure that the task is not always occupied and not used, the problem can be automatically solved by setting a two-week survival time. Set expirationtime.

When the application is executed in the foreground status every time, it is judged and set.

5. The scheduled agent is automatically canceled after two consecutive crash instances:

Since periodic agents and resource-intensive agetns are controlled by the agent, when the agent continuously encounters crash or unexpected errors,

The agent will be stopped and needs to be restarted after the application returns to foreground mode.

> Example:

Because resource-intensive tasks are not easy to present, in this example, periodic tasks are used as the main implementation. In the background agent, website is called a web service program,

 

Update the background title and background content of the secondary tile.

 

A. Create a Web Service for scheduledtaskagent calling. It can be used to update the tile content and send it to IIS after writing;

 

1: [webmethod]
2: Public String getsystemdatetime ()
3 :{
4: // indicates the background content/Title of the tile.
5: Return string. Format ("system: {0}", datetime. Now. tostring ("yyyy/mm/dd hh: mm: SS "));
6 :}

 

B. Create the scheduled task agent, add the Web service reference, and set the non-synchronous update task;

 

B-1. When oninvoke occurs, first declare the Web service object and the book completed event, finally called Web service. But remember not to add yycomplete (),

 

Because the task to be executed by the agent has not been completed.

 

1: protected override void oninvoke (scheduledtask task)
2 :{
3: // todo: Add code to perform your task in background
4: If (task. Name = ptaskname)
5 :{
6: // The soap client element of the initial Web Service
7: bgservice. service1soapclient tsoapclient = new bgservice. service1soapclient ();
8: // the task to be processed by completed
9: tsoapclient. getsystemdatetimecompleted + = new system. eventhandler <bgservice. getsystemdatetimecompletedeventargs>
(Tsoapclient_getsystemdatetimecompleted );
10: tsoapclient. getsystemdatetimeasync ();
11: // If policycomplete () is not added, you must wait until the Web service return value.
12 :}
13: else
14 :{
15: // if the task is not specified, the row is not required.
16: notifycomplete ();
17 :}
18 :}

B-2. Write the content of secondary tile to be updated when Web Service Processing is complete;

 

Note that if the task needs to be executed in a certain period after execution, remember to add the scheduledactionservice. launchfortest command;

 

1: void tsoapclient_getsystemdatetimecompleted (Object sender, bgservice. getsystemdatetimecompletedeventargs E)
2 :{
3: If (E. Error = NULL)
4 :{
5: // find the tile to be updated and the entire format
6: standardtiledata ttiledata = new standardtiledata
7 :{
8: backgroundimage = new uri (string. Format ("/images/42502.16.png", "Taipei"), urikind. Relative ),
9: Title = "BG sample ",
10: Count = 0,
11: backtitle = "getting service ",
12: backcontent = E. result,
13: backbackgroundimage = new uri ("/images/red.png", urikind. Relative)
14 :};
15: shelltile tusedtile = shelltile. activetiles. firstordefault (
16: Tx => Tx. navigationuri. tostring (). Contains (string. Format ("Key = {0}", ptaskname )));
17: If (tusedtile! = NULL)
18 :{
19: tusedtile. Update (ttiledata );
20 :}
21: // if you need a regular row, you must add the following equation section.
22: // scheduledactionservice. launchfortest (ptaskname, timespan. fromseconds (10 ));
23 :}
24: else
25 :{
26: // The user must also send the toast report.
27: shelltoast toast = new shelltoast ();
28: Toast. Title = "error ";
29: Toast. content = E. Error. message;
30: Toast. Show ();
31 :}
32: notifycomplete ();
33 :}

C. Create an application, add the tile and periodic task functions, and add the scheduled task agent and Web Service to the project reference;

 

C-1. Write button events. scheduledtask and tile can be created only when no key is specified in the tile;

 

1: Private void button_click (Object sender, routedeventargs E)
2 :{
3:
4: shelltile tusedtile = shelltile. activetiles. firstordefault (
5: Tx => Tx. navigationuri. tostring (). Contains (string. Format ("Key = {0}", ptaskname )));
6: If (tusedtile = NULL)
7 :{
8: // scheduled task agent
9: gperiodictask = new periodictask (ptaskname );
10: gperiodictask. Description = "bgscheduledaction sample, update tile by webserivce ";
11: scheduledactionservice. Add (gperiodictask );
12: periodicstackpanel. datacontext = gperiodictask;
13: scheduledactionservice. launchfortest (ptaskname, timespan. fromseconds (10 ));
14:
15: // Add Tile
16: standardtiledata ttiledata = new standardtiledata
17 :{
18: backgroundimage = new uri (string. Format ("/images/42502.16.png", "Taipei"), urikind. Relative ),
19: Title = "BG sample ",
20: Count = 0,
21: backtitle = "null ",
22: backcontent = "null ",
23: backbackgroundimage = new uri ("/images/red.png", urikind. Relative)
24 :};
25: // create a secondary tile and specify the page
26: URI Turl = new uri (string. Format ("/mainpage. XAML? Key = {0} ", ptaskname), urikind. Relative );
27: shelltile. Create (Turl, ttiledata );
28 :}
29: else
30 :{
31: MessageBox. Show ("The periodictask already existed !! ");
32 :}
33 :}

C-2. Write the elements that automatically get the specified scheduledaction and bind to the screen when the screen starts;

 

1: // Constructor
2: Public mainpage ()
3 :{
4: initializecomponent ();
5:
6: // search for the specified scheduled Task Name
7: scheduledaction tTask = scheduledactionservice. Find (ptaskname );
8: If (tTask! = NULL)
9 :{
10: // row Data Binding
11: gperiodictask = tTask as periodictask;
12: periodicstackpanel. datacontext = gperiodictask;
13 :}
14 :}

C-3. Write to remove the specified scheduled task when you click checked = false;

 

1: Private void periodiccheckbox_unchecked (Object sender, routedeventargs E)
2 :{
3: // remove periodictask
4: scheduledaction tTask = scheduledactionservice. Find (ptaskname );
5: If (tTask! = NULL)
6: scheduledactionservice. Remove (ptaskname );
7 :}

D. Test Procedure

 

D-1. Open the program and click Start periodic agent, create tile 」;

 

D-2. After tile is created, click the program again to view the periodic agent status;

 

D-3. Press start back to start page note that tile's background content and title have a value from NULL;

 

For example:

 

 

 

 

Source code download

 

 

 

The above is an application used to share and write a background schedule task. This Agent allows the app to write some scheduled messages to the system. In xda, I have seen some applications that write similar schedule tasks, it can directly operate on the information in the screen. I think it is very powerful. It uses the native-code method, so that schedule task can seek to retrieve the picture information. However, I am not very familiar with this method. So in the future, more APIs of WP7 will make it more suitable for everyone's applications.

 

This article from Pou blog, original address: http://www.dotblogs.com.tw/pou/archive/2011/11/27/59664.aspx

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.