In this tutorial, you will learn how to set up a scheduled task within Sitecore CMS. Scheduled tasks are bits of code that run according to a defined schedule with no dependencies. Every major CMS system provides the capability to create and set scheduled tasks and Sitecore is no exception. Personally, I've created hundreds of tasks. These tasks have ranged from syncing content between CMS systems, clearing database logs, populating search indexes, sending notifications, and logging people out of systems. In today's guide, I'm going to cover the basic code structure you need to create a scheduled task in Sitecore and how to enable it within the CMS to run

What Code Do I Need to Create a Sitecore Scheduled Task?

The code to create a scheduled task in Sitecore is pretty straightforward as seen below:

You don't have to implement from any interfaces or inherit from any special base class. You just need to make sure your class has a public method that won't take any parameters. The default Sitecore convention is to call the main executing method Run() method. In the Run() method add the code you want to run. Simples 🙂

Defining Your Scheduled Task in Sitecore

To schedule a task you need to create an agent. If you have ever needed to upgrade or install Sitecore, you know that a lot of the website's configuration settings are done in .config files, either in web.config directly, or, within config files found in the App_Config directory. To define an agent you need to add a new entry in web.config in this element:

Configuration âž¡ Sitecore âž¡ Scheduling

If you look in the sites web.config you'll be able to find a bunch of default Sitecore scheduled tasks in this section. A new task is added by creating a new element. In the element, you define the class to invoke and the time interval of when it should be triggered.

If you are new to Sitecore, it is very strongly recommended that you keep your web.config as stock as possible. This will make upgrading later on, easier. As upgrades usually involve a lot of changes to the config files, it's best to have all your custom configs in their own file that is transformed into the main web.config. The less config that you have to untangle when you upgrade, the easier your life will be. A typical custom .config file that contains the scheduled task registration configuration will look like this:

Assuming that the class created above was compiled into an assembly called Website.Core, my agent definition would look like this:

The second parameter of the element, method, defines the method that will be called on execution. In my example, I'm using the default Sitecore convention for the agent method Run(). The interval parameter defines the time schedule that your scheduled task will be called. If the value is set 00:00:00 your scheduled task will be disabled. That is all you need to know in order to get going with Sitecore scheduled tasks. Happy Coding 🤘