Scheduled tasks
List of examples:
- Creating a scheduled task
- Updating a scheduled task
- Updating multiple scheduled tasks
- Executing a scheduled task
- Deleting a scheduled task
Creating a scheduled task
// Creates a new scheduled task object
TaskInfo newTask = new TaskInfo();
// Sets the basic task properties
newTask.TaskDisplayName = "New task";
newTask.TaskName = "NewTask";
newTask.TaskAssemblyName = "CMS.WorkflowEngine";
newTask.TaskClass = "CMS.WorkflowEngine.ContentPublisher";
newTask.TaskSiteID = SiteContext.CurrentSiteID;
newTask.TaskEnabled = true;
// Creates the scheduling interval for the task
TaskInterval interval = new TaskInterval();
// Sets the interval properties
interval.Period = SchedulingHelper.PERIOD_DAY;
interval.StartTime = DateTime.Now;
interval.Every = 2;
interval.Days = new System.Collections.Generic.List<DayOfWeek>()
{
DayOfWeek.Monday,
DayOfWeek.Sunday,
DayOfWeek.Thursday
};
// Assigns the interval settings to the task
newTask.TaskInterval = SchedulingHelper.EncodeInterval(interval);
// Calculates the first run time for the new task
newTask.TaskNextRunTime = SchedulingHelper.GetFirstRunTime(interval);
// Saves the scheduled task to the database
TaskInfo.Provider.Set(newTask);
Updating a scheduled task
// Gets the scheduled task
TaskInfo updateTask = TaskInfo.Provider.Get("NewTask", SiteContext.CurrentSiteID);
if (updateTask != null)
{
// Updates the task properties
updateTask.TaskDisplayName = updateTask.TaskDisplayName.ToLowerCSafe();
// Saves the updated task to the database
TaskInfo.Provider.Set(updateTask);
}
Updating multiple scheduled tasks
// Gets all enabled scheduled tasks whose code name starts with 'New'
var tasks = TaskInfo.Provider.Get()
.WhereStartsWith("TaskName", "New")
.WhereEquals("TaskEnabled", 1);
// Loops through individual tasks
foreach (TaskInfo task in tasks)
{
// Updates the task properties
task.TaskDisplayName = task.TaskDisplayName.ToUpper();
// Saves the updated task to the database
TaskInfo.Provider.Set(task);
}
Executing a scheduled task
// Gets the scheduled task
TaskInfo runTask = TaskInfo.Provider.Get("NewTask", SiteContext.CurrentSiteID);
if (runTask != null)
{
// Executes (runs) the task, regardless of its interval settings
SchedulingExecutor.ExecuteTask(runTask);
}
Deleting a scheduled task
// Gets the scheduled task
TaskInfo deleteTask = TaskInfo.Provider.Get("NewTask", SiteContext.CurrentSiteID);
if (deleteTask != null)
{
// Deletes the scheduled task
TaskInfo.Provider.Delete(deleteTask);
}