Having scheduled re-occurring tasks is a very common website requirement, and is the reason why almost all of the major CMS systems provide some way to create and set scheduled tasks and Sitecore is no exception. From past projects, I've created scheduled tasks to sync content from CMS systems, clear database logs, send emails, log people out of systems and probably a number of other things I've forgotten about now. 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 that task so it runs.
What Code Do I Need to Create a Sitecore Scheduled Task?
The code to create a scheduled task in Sitecore is pretty straightforward:
You don't have to implement any interfaces, or classes. 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 this method Run() method. In the Run() method add the code you want to run.
Defining Your Scheduled Task in Sitecore
If you have ever needed to upgrade or install Sitecore, then you will know a lot of your website's configuration settings are done in .config files, either in the web.config, or, the 'App_Config' directory. Creating your own custom scheduling agent is very similar. To define an agent you need to add a new entry in:
If you look in your web.config you'll be able to find a bunch of default Sitecore scheduled tasks in this section. Each new task is added using an element. In the element you define the class to invoke and the time interval it should run under. If you are new to Sitecore it is very strongly recommended that you keep your web.config as stock as possible so upgrading, later on, is easier.
As upgrades usually involve a lot of changes to the config files, it's best to have all your custom configs in its own file. The less you have to untangle the easier your life will be. A typical custom .config files which add a custom scheduler, will look like the following:
Using the code for the scheduled task above and assuming that class was compiled into an assembly called, Website.Core assembly, my agent definition would look like this:
The second parameter of the tag, '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 value is set to nothing, e.g. '00:00:00' your scheduled task will be disabled.