Make Long Running Scheduled Agents Async

Sitecore’s Scheduled Agents and Tasks have been around forever and are well-known members of the XM suite. Less known is a gotcha you might run into when implementing long running operations (i.E. background import/export, bulk updates,…)

Why is that? Scheduled Agents and Tasks all run synchronously unless you tell them not to.

An example

This agent will be executed every 2 hours:

<agent 
    type="MyLongRunningOperation,MyAssembly" 
    method="Run" 
    interval="02:00:00"/>

Code:

public class MyLongRunningOperation
{
	public void Run()
	{
		// Do some time consuming things
	}
}

Scheduler will launch the Run() method in a new thread, but it will wait for it to be completed preventing other agents from running until this operation completes.

This can lead to various strange behaviour i.E. a long running operation might never complete because it blocks the Sitecore.Tasks.UrlAgent from keeping your instance alive.

JobManager to the rescue

Case A: Scheduled Agents

A possible workaround might be the following:

public class MyLongRunningOperation
{
	public void Run()
	{
		var options = new DefaultJobOptions("MyLongRunningOperation Job", "MyCategory", "my_site", this,
			"DoTimeConsumingThings");
		JobManager.Start(options);
	}

	public void DoTimeConsumingThings()
	{
		// Do some time consuming things
	}
}

This will call the DoTimeConsumingThings() method in a background job through JobManager. It will be visible as “MyLongRunningOperation Job” on /sitecore/admin/jobs.aspx

The neat thing is: You can forget the workaround above! Just add the async=”true” attribute to your agent configuration and Scheduler will take care of it automatically:

<agent 
    type="MyLongRunningOperation,MyAssembly" 
    method="Run" 
    interval="02:00:00" 
    async="true"/>

This tells Scheduler to not wait for job completion and continue with the other agents.

Case B: Scheduled Tasks

Tasks defined as Sitecore Items have an async checkbox which tells Sitecore.DatabaseAgent to run them as Job.

DatabaseAgent will then launch this command as a background job and you’ll see it appear as ScheduleCommand ‘{item-id-of-command}’ on /sitecore/admin/jobs.aspx

Caveat: Different context

Be aware that the the site context and default device might be different than expected when running asynchronously.

TL;DR

Sitecore Scheduled Agents and Tasks run synchronously unless you explicitly set them to async. You can do this by adding the asnyc=”true” attribute in your agent configuration OR by checking the “Async” checkbox on Scheduled Tasks.

,

Leave a Reply

Your email address will not be published. Required fields are marked *