Monday, April 21, 2008

Adding Custom Scheduled Agents

After you get yourself familiar with the logic of Sitecore Scheduler, you may be interested in creating your own custom scheduled agent.

There are two ways of doing that. The most elegant way is to create a "task" and a "schedule" item under the "/sitecore/system/Tasks" in the master database as described in this article. After you create a command referencing a class that you develop and a schedule item to set the timing parameters, the out-of-the-box DatabaseAgent will pick it up on the scheduled basis according to its interval parameter (remember the loop nature of things). By default, there are two DatabaseAgents defined in the system. One is for the "master" database, another for "core". This should be kept in mind since in the staged environments when the content delivery server does not have access to neither core nor master database, you may need to adjust it and change the "database" parameter to "web" as your schedule item definitions should be published anyway.

There is another way to approach the creation of the custom scheduled agents and you may already guessed it. You can simply develop an agent class (see below), compile it and provide the definition of your custom agent to the Sitecore Scheduler by defining it in the web.config:

   1: <scheduling>
   2:   <frequency>00:00:10</frequency>
   3:   <!-- default agents go here... -->
   4:   <agent type="MyProj.MyAgent, MyDLL" method="Run" interval="00:10:00">
   5:     <param desc="myparam">valueofmyparam</param>
   6:   </agent>
   7: </scheduling>

The reference in the "type" attribute should correspond the existing class within existing assembly in the "bin" directory as usual.

The skeleton of any custom agent is shown below. You can dynamically pass different string parameters to your agent:

   1: public class MyAgent
   2: {
   3:     // one string parameter that can be passed from the web.config definition
   4:     private string myparam;
   6:     // Constructor
   7:     // Notice that it expects the parameter from the agent definition
   8:     public MyAgent(string myparam)
   9:     {
  10:         this.myparam = myparam;
  11:     }
  13:     // A method that is dynamically executed by Sitecore Scheduler
  14:     public void Run()
  15:     {
  16:         // do your processing here
  17:     }
  18: }

Enjoy responsibly.