Kentico CMS 7.0 Developer's Guide

Scheduling custom code

Scheduling custom code

Previous topic Next topic Mail us feedback on this topic!  

Scheduling custom code

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

The process of scheduling a custom task includes two steps:

 

Writing the code that performs the required actions

Registering a new scheduled task in the CMS

 

Writing the task code

 

You need to define each scheduled task as a class that implements the CMS.Scheduler.ITask interface. To integrate this type of class into the application, you can:

 

Create a new assembly (Class library) in your web project and include the task class there. In this case, you must add the appropriate references to both the assembly and the main CMS project.

Define the scheduled task in App_Code and load the class via the API. This ensures that the system automatically compiles the task and you do not need to use a separate assembly. The example below uses this approach.

 

Example

 

1. Open your web project in Visual Studio and add a new class into the App_Code folder (or Old_App_Code if the project is installed as a web application). For example, name the class CustomTask.cs.

 

2. Edit the class and add the following references:

 

[C#]

 

using CMS.EventLog;
using CMS.Scheduler;

 

3. (Optional) Wrap the class into the Custom namespace.

 

[C#]

 

namespace Custom
{
    /// <summary>
    /// Custom task class.
    /// </summary>
    public class CustomTask
    {
 
    }
}

 

4. Make the class implement the ITask interface.

 

[C#]

 

public class CustomTask: ITask

 

5. Define the Execute method in the class:

 

[C#]

 

/// <summary>
/// Executes the task.
/// </summary>
/// <param name="ti">Info object representing the scheduled task</param>
public string Execute(TaskInfo ti)
{
    string detail = "Executed from '~/App_Code/CustomTask.cs'. Task data:"
                    + ti.TaskData;
 
    // Logs the execution of the task in the event log.
    EventLogProvider.LogInformation("CustomTask""Execute", detail);
 
    return null;
}

 

You must always include the Execute method when writing a scheduled task. The system calls this method whenever the given task is executed, so it needs to contain all code implementing the required functionality. In this example, the task only creates a record in the application's event log so that you can confirm it is being executed.

 

The TaskInfo parameter of the method allows you to access the data fields of the corresponding scheduled task object. The sample code adds the content of the TaskData field into the details of the event log entry.

 

The string returned by the method is displayed in the administration interface as the result of the task's most recent execution. You can leave it as null in this case.

 

Loading App_Code task classes

 

For tasks added to the App_Code folder, you must ensure that the system loads the appropriate class when executing the scheduled task. You can find additional information related to this topic in Registering custom classes in App_Code.

 

1. Create another class in the App_Code folder (or Old_App_Code if the project is installed as a web application). For example, name the class ClassLoader.cs.

 

2. Edit the class and add the following reference:

 

[C#]

 

using CMS.SettingsProvider;

 

3. Delete the default class declaration and its content. Instead, extend the CMSModuleLoader partial class and define a new attribute inheriting from CMS.SettingsProvider.CMSLoaderAttribute:

 
[C#]

 

[ClassLoader]
public partial class CMSModuleLoader
{
    /// <summary>
    /// Attribute class for loading custom classes.
    /// </summary>
    private class ClassLoader : CMSLoaderAttribute
    {
 
    }
}

 

4. Enter the following code into the ClassLoader attribute class:

 

[C#]

 

/// <summary>
/// Called automatically when the application starts.
/// </summary>
public override void Init()
{
    // Assigns a handler for the OnGetCustomClass event.
    ClassHelper.OnGetCustomClass += ClassHelper_OnGetCustomClass;
}
 
/// <summary>
/// Gets a custom class object based on the given parameters.
/// </summary>
private void ClassHelper_OnGetCustomClass(object sender, ClassEventArgs e)
{
    if (e.Object == null)
    {
        // Checks the name of the requested class.
        switch (e.ClassName)
        {
            // Gets an instance of the CustomTask class.
            case "Custom.CustomTask":
                e.Object = new Custom.CustomTask();
                break;
        }
    }
}

 

In the case of scheduled tasks, the value of the ClassName property of the ClassHelper_OnGetCustomClass handler's ClassEventArgs parameter matches the Task class name specified for the given task (Custom.CustomTask in this example). The handler checks the class name to identify which specific task is being executed and then passes on an instance of the appropriate class.

 

Registering new scheduled tasks

 

1. Go to Site Manager -> Administration -> Scheduled tasks and select the Site for which you wish to schedule the task (global) if it should be performed for all sites or affect global objects).

 

2. Click NewTask New task and fill in the properties of the task:

 

Task display name

Sets a name for the task that is shown in the administration interface.

Task name

Sets a unique name that serves as an identifier for the scheduled task, for example in the API. You can leave the (automatic) option to have the system generate an appropriate code name based on the display name.

Task assembly name

Specifies the name of the assembly where the task is implemented.

 

Enter App_Code for tasks implemented in the App_Code folder.

Task class name

Specifies the exact class (including any namespaces) that defines the functionality of the scheduled task.

 

Enter Custom.CustomTask to load the task class created in the example sections above.

Task interval

Sets the time interval between two executions of the task.

 

This does not ensure that the task will be executed at the exact time, only that it will be considered ready for execution. The precise execution time depends on the general settings of the scheduler.

Task data

Additional data provided to the task's class. This field can be accessed from the code of the task, so you may use as a parameter to easily modify the task without having to edit its implementation.

Task condition

Allows you to enter an additional macro condition that must be fulfilled in order for the scheduler to execute the task.

 

You can write any condition according to your specific requirements. For details about available macro options and syntax, refer to the Development -> Macro expressions chapter.

 

Clicking on the edit icon (Edit) opens the Macro condition editor, which allows you to build conditions through a graphical interface. The Clear condition (ClearCondition) action removes the current content of the condition field.

Task enabled

This field must be enabled in order for the task to be scheduled.

Delete task after last run

Indicates if the system should delete the task after its final run (applicable if the task is set to run only once).

Run task in separate thread

Indicates if the scheduler should execute the task in a separate thread to improve application performance.

 

It is not possible to access context data (information about the current page, user, etc.) in the code of tasks that are executed in a separate thread.

Use external service

If enabled, the task is processed by the Scheduler Windows service instead of the web application. If the Use external service setting in Site Manager -> Settings -> System is disabled, even tasks with this option enabled are processed by the application itself. Only some of the default scheduled tasks support this option. The ones that do not have it available in their editing interfaces must be processed by the application itself.

 

You cannot define the task in the App_Code folder if you wish to use the external service. To run a custom task externally, you must add a new assembly to your project and then define the task class there.

Run individually for each site

This option is only available for global tasks. If enabled, the scheduler executes the task repeatedly as a site‑specific task, once for each running site in the system. The task automatically runs within the context of the corresponding site.

 

This can be useful if you wish to manage a task in a single location instead of creating a separate one for every site.

Server name

Sets the name of the web farm server where the task is executed. This field is applicable only if your application is running in a Web farm environment.

 

To add a new task for all web farm servers currently registered in the system, check the Create tasks for all web farm servers box below the field.

Use context of user

If the scheduled task needs to access data from the user context in its code (e.g. to check permissions), you can use this property to choose which user is provided. The scheduler always executes the task within the context of the selected user.

 

In most cases, the user context does not affect the functionality of the task, and you can leave the (default) option — the context of a public user is used.

Executions

Shows how many times the task has been executed. You can reset this counter back to 0 by clicking Reset.

 

devguide_clip1228

 

3. Click Save Save.

 

The task will now be executed regularly according to the specified interval.

 

Result

 

To check the result of the sample custom task, go to Site Manager -> Administration -> Event log and look for entries with CustomTask as their Source.

 

devguide_clip1478