Getting Started

This example will assume you have a Windows service you are creating called "CadenceWindowsService".

  • Download and build Cadence.NET.
  • In your solution, add either a project reference or a binary reference to Cadence.NET.
  • Add three folders to your Service project called "TaskContexts", "TaskManagers", and "Tasks"
  • Add a new file called "SampleTask.cs" to the Tasks folder
  • Add a new file called "SampleTaskContext.cs" to the "TaskContexts" folder
  • Add a new file called "SampleTaskManager.cs" to the "TaskManagers" folder

These files exist in the downloaded source code, so you can just copy them over.,

All tasks should inherit from Task. Optionally, you can include the TaskBehavior attribute to define how you'd like this task to behave when it runs.

Creating a Task

[TaskBehavior(RunConcurrent = false, RunAsynch = false)]
public class SampleTask : Task
{
    public override void PerformTask(SampleTaskContext context)
    {
        try
        {
            // Raise the start event 
            OnTaskStarted(context);
 
            // Do some work 
 
            // Raise the completed event 
            OnTaskCompleted(context);
        }
        catch (Exception exc)
        {
            context.ErrorContext = exc; OnTaskError(context);
        }
    }
}

 

The SampleTaskContext should inherit from TaskContext. It will provide the basic properties for tracking exceptions and determining last run, run time, and error states.

Finally, the SampleTaskManager should inherit from TaskManager. It it, you will create a reference to SampleTask, provide the run parameters (Calendars), and set the Interval. See the example below:

Creating a Task Manager

public class SampleTaskManager : CadenceTaskManager
{
    public SampleTaskManager()
    {
        // Create a sample task and apply the context and event listeners 
        SampleTask sampleTask = new SampleTask(); sampleTask.TaskContext = new SampleTaskContext();
 
        // Add our event handlers 
        sampleTask.TaskError += new Task.TaskErrorEventHandler(TaskError);
        sampleTask.TaskStarted += new Task.TaskStartedEventHandler(TaskStarted);
        sampleTask.TaskCompleted += new Task.TaskCompletedEventHandler(TaskCompleted);
 
        sampleTask.Calendars = new List<ICalendar>(); 
        
        // Only run the tasks on Mondays and Wednesdays, in EST timezone 
        sampleTask.Calendars.Add(new DailyCalendar( Monday: true, Wednesday: true )
            { TimezoneUTCOffset = -4 }
        );
 
        // Only run the tasks between 1:30PM and 2:30PM EST 
        sampleTask.Calendars.Add(new HourlyCalendar() {
            StartTime = new Time(hour: 13, minute: 30),
            EndTime = new Time(hour: 14, minute: 30),
            TimezoneUTCOffset = -4
        });
 
        // Create a new task list and add our task 
        Tasks = new List<Task>(); Tasks.Add(sampleTask);
 
        // Set the interval to run every 15 seconds forever, with exact precision, 
        // meaning the interval will adjust itself based on run times of the tasks. 
 
        Interval = new Interval() {
            Schedule = new Time() { Second = 15 },
            RunOptions = Cadence.NET.Interval.IntervalRunOptions.RunInfinite,
            Precision = Cadence.NET.Interval.IntervalPrecision.Exact
        };
    }
}

You've framed out your task, now it's time to invoke it!

In your service class, in the OnStart event, add the following code:

Invoking the Task Manager

protected override void OnStart(string[] args)
{
    try
    {
        log.Info("Service is starting.");
 
        SampleTaskManager taskMan = new SampleTaskManager();
        taskMan.Start();
 
        log.Info("Service is ready.");
    }
    catch (Exception exc)
    {
        log.Error(exc);
    }
}

Using the REST API

Cadence.NET ships with a very simple internal webserver that exposes some basic REST commands. To utilize the webserver in your application, just set the "WebserverListenerAddress" value in your app.config file (e.g. "http://localhost:8080/Cadence". 

When your service is online and running, you can access this URL with a web browser to get a JSON representation of the status of your task manager. It will display a list of all & active tasks, information about the manager itself (interval, RunOnce), and a list of REST commands.

  • StopManager
    • This will nullify the timer, rendering the service inactive. Successful responses return a HTTP 200/OK code.
  • StartManager
    • If the manager is in a stopped state, this will call the Start() method of the manager. Successful responses return a HTTP 200/OK code.
  • FlushActiveTasks
    • This will remove any tasks that are currently in the active queue. Successful responses return a HTTP 200/OK code.
  • FlushTasks
    • This will remove all tasks from the manager. Successful responses return a HTTP 200/OK code.
  • ResetTimer
    • This will reset the task timer to its original start state.
  • AddTask
    • Adds a task to the Task list. This command requires that AssemblyName and TypeName arguments are provided (e.g. AddTask/Cadence.NET/Cadence.NET.Examples.SampleTask). This will create a default instance of the task and add it to the task list. Successful responses return a HTTP 200/OK code.
  • RemoveTask
    • Removes a task from the Task list. This command requires that AssemblyName and TypeName arguments are provided (e.g. AddTask/Cadence.NET/Cadence.NET.Examples.SampleTask). This will look for the instance of a task with the provided assembly name and type name and, if found, remove it from the list. Successful responses return a HTTP 200/OK code.
  • ShowLogs
    • Only available when browsing locally or if the request is authenticated. Will display the entire contents of the log4net file appender to the browser. Successful responses return a HTTP 200/OK code.

For more information see the Webserver.cs file located in the BaseClasses folder. The webserver implementation is based on the following work: http://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server.aspx.

Last edited Oct 20, 2016 at 3:29 PM by Usualdosage, version 20