Windows Phone came through long way after it’s initial release on Oct 21st 2010.  Windows Phone 7.5 update release called as “MANGO” brought lots of improvements including Multi tasking capabilities etc. With the introduction of multi-tasking ( it is not true multi tasking, but an efficient application switching which ensures that only one application will reside in memory and remaining running applications will be in deactivated stage. Since the application is not killed, it can be launched faster – that gives the capability similar to true multi tasking).

What is Background Agents?

Background agents feature allows you to run certain code in a background thread and scheduled tasks  are that runs periodically.

Scheduled Tasks and background agents allow an application to execute code in the background, even when the application is not running in the foreground. The different types of Scheduled Tasks are designed for different types of background processing scenarios and therefore have different behaviors and constraints.

Note: that Background agents are not supported in 256MB devices. Only initial 512MB devices with Windows Phone “MANGO” would be able to run background agents

 

There are types of scheduled tasks or Background Agents and they are:

1. Periodic Task Agents- Periodic task agents will run for a short period of time and does a certain predefined operations defined by you. It also have the capability to run based on certain time interval.

A typical example would be checking whether device is having network connectivity periodically or checking any mails available with mail server etc.

2. Resource Intensive Task Agents- Resource Intensive tasks agents will run for a long period if all your network connectivity(if you need some network processing while doing the task) and power and resource usage etc.

A Typical example of scenario would be your phone receiving some application data updates and additional feature set update etc.

 

Using Background Agents:

1. To start with Scheduled tasks agents are part of Microsoft.Phone.Scheduler namespace

2. Create a new Windows Phone Scheduled Task project in your Windows Phone solution

image

3. Click on “OK” and Now I created a Windows Phone Scheduled Task project called  “ScheduledTaskAgent1

and this is how the initial code generated by Visual Studio will appear

using System.Windows;
using Microsoft.Phone.Scheduler;

namespace ScheduledTaskAgent1
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background

            NotifyComplete();
        }
    }
}

Now you can see there is an OnInvoke(ScheduledTask task) method, inside that method we will define our Periodic or Resource Intensive tasks implementation.

 

4. Now it is the time for us to do our implementation.  (This sample I have taken from MSDN Reference on How to: Implement Background Agents for Windows Phone)

         a.) Scheduled Task Code Implementation (this code will send toast messages, so that you can see that when your application is running in background. )

 /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {

              //TODO: Add code to perform your task in background
              string toastMessage = "";

              // If your application uses both PeriodicTask and ResourceIntensiveTask
              // you can branch your application code here. Otherwise, you don't need to.
              if (task is PeriodicTask)
              {
                // Execute periodic task actions here.
                toastMessage = "Periodic task are running.";
              }
              else
              {
                // Execute resource-intensive task actions here.
                toastMessage = "Resource-intensive task are running.";
              }

              // Launch a toast to show that the agent is running.
              // The toast will not be shown if the foreground application is running.
              ShellToast toast = new ShellToast();
              toast.Title = "Background Agent Sample";
              toast.Content = toastMessage;
              toast.Show();

              // If debugging is enabled, launch the agent again in one minute.
            #if DEBUG_AGENT
              ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
            #endif

              // Call NotifyComplete to let the system know the agent is done working.


            NotifyComplete();
        }

     

     b.) MainPage.xaml  markup

<span style="color: blue">&lt;</span><span style="color: #a31515">phone</span><span style="color: blue">:</span><span style="color: #a31515">PhoneApplicationPage 
    </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Class</span><span style="color: blue">=&quot;PhoneApp1.MainPage&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">x</span><span style="color: blue">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">phone</span><span style="color: blue">=&quot;clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">shell</span><span style="color: blue">=&quot;clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">d</span><span style="color: blue">=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">mc</span><span style="color: blue">=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    </span><span style="color: red">mc</span><span style="color: blue">:</span><span style="color: red">Ignorable</span><span style="color: blue">=&quot;d&quot; </span><span style="color: red">d</span><span style="color: blue">:</span><span style="color: red">DesignWidth</span><span style="color: blue">=&quot;480&quot; </span><span style="color: red">d</span><span style="color: blue">:</span><span style="color: red">DesignHeight</span><span style="color: blue">=&quot;768&quot;
    </span><span style="color: red">FontFamily</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneFontFamilyNormal</span><span style="color: blue">}&quot;
    </span><span style="color: red">FontSize</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneFontSizeNormal</span><span style="color: blue">}&quot;
    </span><span style="color: red">Foreground</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneForegroundBrush</span><span style="color: blue">}&quot;
    </span><span style="color: red">SupportedOrientations</span><span style="color: blue">=&quot;Portrait&quot; </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Portrait&quot;
    </span><span style="color: red">shell</span><span style="color: blue">:</span><span style="color: red">SystemTray.IsVisible</span><span style="color: blue">=&quot;True&quot;&gt;

    </span><span style="color: green">&lt;!--LayoutRoot is the root grid where all page content is placed--&gt;
    </span><span style="color: blue">&lt;</span><span style="color: #a31515">Grid </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;LayoutRoot&quot; </span><span style="color: red">Background</span><span style="color: blue">=&quot;Transparent&quot;&gt;
        &lt;</span><span style="color: #a31515">Grid.RowDefinitions</span><span style="color: blue">&gt;
            &lt;</span><span style="color: #a31515">RowDefinition </span><span style="color: red">Height</span><span style="color: blue">=&quot;Auto&quot;/&gt;
            &lt;</span><span style="color: #a31515">RowDefinition </span><span style="color: red">Height</span><span style="color: blue">=&quot;*&quot;/&gt;
        &lt;/</span><span style="color: #a31515">Grid.RowDefinitions</span><span style="color: blue">&gt;

        </span><span style="color: green">&lt;!--TitlePanel contains the name of the application and page title--&gt;
        </span><span style="color: blue">&lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;TitlePanel&quot; </span><span style="color: red">Grid.Row</span><span style="color: blue">=&quot;0&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;12,17,0,28&quot;&gt;
            &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;ApplicationTitle&quot; </span><span style="color: red">Text</span><span style="color: blue">=&quot;Craziness App&quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextNormalStyle</span><span style="color: blue">}&quot;/&gt;
            &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;PageTitle&quot; </span><span style="color: red">Text</span><span style="color: blue">=&quot;Tasks Sample&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;9,-7,0,0&quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle1Style</span><span style="color: blue">}&quot;/&gt;
        &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;

        </span><span style="color: green">&lt;!--ContentPanel - place additional content here--&gt;
        </span><span style="color: blue">&lt;</span><span style="color: #a31515">Grid </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">=&quot;ContentPanel&quot; </span><span style="color: red">Grid.Row</span><span style="color: blue">=&quot;1&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;12,0,12,0&quot;&gt;

            &lt;</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                &lt;</span><span style="color: #a31515">StackPanel  </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Vertical&quot; </span><span style="color: red">Name</span><span style="color: blue">=&quot;PeriodicStackPanel&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;0,0,0,40&quot;&gt;
                    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;Periodic Agent&quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle2Style</span><span style="color: blue">}&quot;/&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;name: &quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Name</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;is enabled&quot; </span><span style="color: red">VerticalAlignment</span><span style="color: blue">=&quot;Center&quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">CheckBox </span><span style="color: red">Name</span><span style="color: blue">=&quot;PeriodicCheckBox&quot; </span><span style="color: red">IsChecked</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">IsEnabled</span><span style="color: blue">}&quot; </span><span style="color: red">Checked</span><span style="color: blue">=&quot;PeriodicCheckBox_Checked&quot; </span><span style="color: red">Unchecked</span><span style="color: blue">=&quot;PeriodicCheckBox_Unchecked&quot;/&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;is scheduled: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">IsScheduled</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;last scheduled time: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">LastScheduledTime</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;expiration time: &quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">ExpirationTime</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;last exit reason: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">LastExitReason</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                &lt;</span><span style="color: #a31515">StackPanel  </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Vertical&quot; </span><span style="color: red">Name</span><span style="color: blue">=&quot;ResourceIntensiveStackPanel&quot; </span><span style="color: red">Margin</span><span style="color: blue">=&quot;0,0,0,40&quot;&gt;
                    &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;Resource-intensive Agent&quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle2Style</span><span style="color: blue">}&quot;/&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;name: &quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">Name</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;is enabled&quot; </span><span style="color: red">VerticalAlignment</span><span style="color: blue">=&quot;Center&quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">CheckBox </span><span style="color: red">Name</span><span style="color: blue">=&quot;ResourceIntensiveCheckBox&quot; </span><span style="color: red">IsChecked</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">IsEnabled</span><span style="color: blue">}&quot; </span><span style="color: red">Checked</span><span style="color: blue">=&quot;ResourceIntensiveCheckBox_Checked&quot; </span><span style="color: red">Unchecked</span><span style="color: blue">=&quot;ResourceIntensiveCheckBox_Unchecked&quot;/&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;is scheduled: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">IsScheduled</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;last scheduled time: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">LastScheduledTime</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;expiration time: &quot; </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">ExpirationTime</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                    &lt;</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">=&quot;Horizontal&quot;&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;last exit reason: &quot;  </span><span style="color: red">Style</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}&quot;/&gt;
                        &lt;</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">=&quot;{</span><span style="color: #a31515">Binding </span><span style="color: red">LastExitReason</span><span style="color: blue">}&quot; /&gt;
                    &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
                &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;
            &lt;/</span><span style="color: #a31515">StackPanel</span><span style="color: blue">&gt;


        &lt;/</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">Grid</span><span style="color: blue">&gt;
 
    </span><span style="color: green">&lt;!--Sample code showing usage of ApplicationBar--&gt;
    &lt;!--&lt;phone:PhoneApplicationPage.ApplicationBar&gt;
        &lt;shell:ApplicationBar IsVisible=&quot;True&quot; IsMenuEnabled=&quot;True&quot;&gt;
            &lt;shell:ApplicationBarIconButton IconUri=&quot;/Images/appbar_button1.png&quot; Text=&quot;Button 1&quot;/&gt;
            &lt;shell:ApplicationBarIconButton IconUri=&quot;/Images/appbar_button2.png&quot; Text=&quot;Button 2&quot;/&gt;
            &lt;shell:ApplicationBar.MenuItems&gt;
                &lt;shell:ApplicationBarMenuItem Text=&quot;MenuItem 1&quot;/&gt;
                &lt;shell:ApplicationBarMenuItem Text=&quot;MenuItem 2&quot;/&gt;
            &lt;/shell:ApplicationBar.MenuItems&gt;
        &lt;/shell:ApplicationBar&gt;
    &lt;/phone:PhoneApplicationPage.ApplicationBar&gt;--&gt;

</span><span style="color: blue">&lt;/</span><span style="color: #a31515">phone</span><span style="color: blue">:</span><span style="color: #a31515">PhoneApplicationPage</span><span style="color: blue">&gt;
</span>

and this is how my application screen would look like

image

   c. MainPage.xaml.cs implementation

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Tasks;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        PeriodicTask periodicTask;
        ResourceIntensiveTask resourceIntensiveTask;

        string periodicTaskName = "PeriodicAgent";
        string resourceIntensiveTaskName = "ResourceIntensiveAgent";
        public bool agentsAreEnabled = true;
        bool ignoreCheckBoxEvents = false;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            
         
        }



        private void StartPeriodicAgent()
        {
            // Variable for tracking enabled status of background agents for this app.
            agentsAreEnabled = true;

            // Obtain a reference to the period task, if one exists
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "This demonstrates a periodic task.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);
                PeriodicStackPanel.DataContext = periodicTask;

                // If debugging is enabled, use LaunchForTest to launch the agent in 30 seconds.
             //   #if(DEBUG_AGENT)
                    ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(30));
                //#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;
                    PeriodicCheckBox.IsChecked = false;
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.

                }
                PeriodicCheckBox.IsChecked = false;
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
                PeriodicCheckBox.IsChecked = false;
            }
        }


        private void StartResourceIntensiveAgent()
        {
            // Variable for tracking enabled status of background agents for this app.
            agentsAreEnabled = true;

            resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as ResourceIntensiveTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule.
            if (resourceIntensiveTask != null)
            {
                RemoveAgent(resourceIntensiveTaskName);
            }

            resourceIntensiveTask = new ResourceIntensiveTask(resourceIntensiveTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            resourceIntensiveTask.Description = "This demonstrates a resource-intensive task.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(resourceIntensiveTask);
                ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask;

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
                //#if(DEBUG_AGENT)
                    ScheduledActionService.LaunchForTest(resourceIntensiveTaskName, TimeSpan.FromSeconds(60));
                //#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;

                }
                ResourceIntensiveCheckBox.IsChecked = false;
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
                ResourceIntensiveCheckBox.IsChecked = false;
            }


        }

        private void PeriodicCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            StartPeriodicAgent();
        }
        private void PeriodicCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            RemoveAgent(periodicTaskName);
        }
        private void ResourceIntensiveCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            StartResourceIntensiveAgent();
        }
        private void ResourceIntensiveCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            RemoveAgent(resourceIntensiveTaskName);
        }


        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            ignoreCheckBoxEvents = true;

            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            if (periodicTask != null)
            {
                PeriodicStackPanel.DataContext = periodicTask;
            }

            resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as ResourceIntensiveTask;
            if (resourceIntensiveTask != null)
            {
                ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask;
            }

            ignoreCheckBoxEvents = false;

        }




        private void RemoveAgent(string name)
        {
            try
            {
                ScheduledActionService.Remove(name);
            }
            catch (Exception)
            {
            }
        }

    }
}

             

 d.) and Hit “F5” Smile

 

and below are some screen shots for reference.

  1. App is running and Periodic Agent is enabled to run on every 30 seconds.

image

now after 30 seconds scheduled tasks run and called the Scheduled Task implementation

image

 

and can see that last run status is updated and last run reason is completed.

image

 

Apologies for the Poor formatting.

Hope the code is self explanatory and since the Post is so big after the code blocks and screen shots, I am not including much explanations of this sample. You can read MSDN Reference on How to: Implement Background Agents for Windows Phone, which includes clear cut explanation of the above sample.

References:

Background Agents Overview for Windows Phone

How to: Implement Background Agents for Windows Phone