Using DemiCode Scheduler with a custom task

Monday, November 24, 2008

This sample shows how to use DemiCode Scheduler with a custom task programmatically in C#.

The custom task

For this sample we will use the ApplicationTask that ships with DemiCode Scheduler. Most of the code is omitted here for brevity, but the overall pattern of how tasks are implemented is shown:

  • The constructor initializes the task object and should take any parameters required by the task. If the task is used with configuration files DemiCode Scheduler will pass values to these parameters automatically.
  • The Execute method will be called by DemiCode Scheduler and should perform the main objective of the task.

Note: the code for this task is also available in the ApplicationTaskConsole sample available with the product.

public class ApplicationTask : ITask
{
        public void Execute(ILoggerFactory loggerFactory)
        {
                // 
        }

        public ApplicationTask(string path, params string[] arguments)
        {
                // ...
        }
}

The code

The following code instantiates a Scheduler, adds a schedule instance and a task instance and finally starts up schedule execution.

// 1. Create a scheduler
using (Scheduler scheduler = SchedulerFactory.Create())
{
	// 2. Create one (or more) schedules
	IntervalSchedule schedule = new IntervalSchedule(DateTime.Now, TimeSpan.FromSeconds(5));
	scheduler.Add(schedule);

	// 3. Create our task
	ApplicationTask task = new ApplicationTask("cmd", "/K \"echo Application executed\"");
	scheduler.Tasks.Add(task);

	// 4. Start the engine
	scheduler.Start();

	// 5. Wait for user input
	Console.WriteLine("Press [ENTER] to exit");
	Console.ReadLine();

	// 7. Stop the engine
	scheduler.Stop();
}