Thanks for visiting my blog!
After my recent post on Periodic Agents, I had a number of people react to specific parts of the API. Let’s discuss each of these separately.
Periodic Agents’ 14-day Lifespan
It seems that developers are confused about the role periodic agents have with their apps. The short version of the story is that periodic agents are supposed to support your app, not replace it. To this end a periodic agent must be re-registered at least every fourteen days. Typically this is accomplished by re-registering your app on every startup.
So I am curious as to whether people are building apps they think only have background agent functionality. My typical thought about periodic agents is that they are to get the user to come back to my app. If I am doing work in the background for two weeks and can’t coax the user into launching the app, then the app isn’t worthwhile for the user. Am I wrong?
Running a Periodic Agent from the App
As you may have seen from my recent post on Periodic Agents, you can debug an agent by using ScheduledActionService.LaunchForTest. I’ve gotten a bunch of people who asked me if they could run this from published applications. The Marketplace certification doesn’t mind if you use this API but I am confused why you would do this. Agents are under much more stringent runtime limitations than your application so why run code under those limitations? I think what these developers really want is to run the code in their agent…not run their agent. And this is remarkably simple.
The trick is to put the code you need to launch from both places in a shared library. For example, you can see here a Windows Phone 7 application in Visual Studio’s Solution Explorer:
**TheApp **is the main WP7 application that the user launches; **TheAgent **is the Periodic Agent; and **SharedCode **is a shared library that both use. If you put operation that you typically do in a Periodic Agent into a shared library, then you can call it from your app as well without having to execute **TheAgent **at runtime.
In this scenario, TheApp references both TheAgent and SharedCode. TheAgent references SharedCode. This way the same code in OnInvoke in the Periodic Agent can be used in your application as shown below:
// In the Periodic Agent
protected override void OnInvoke(ScheduledTask task)
{
// Code in a shared library
var obj = new SomeCode();
obj.SomeOperation();
NotifyComplete();
}
// In the Main Application
void MainPage_Tap(object sender, GestureEventArgs e)
{
// Shared Code
var obj = new SomeCode();
obj.SomeOperation();
}
This should remove the necessity to ever execute the Periodic Agent from your application.