Click here to Skip to main content
Click here to Skip to main content

A Task Scheduler Library for .NET Applications

, 10 Jun 2014 MIT
Rate this:
Please Sign up or sign in to vote.
A simple task scheduler utility by which you can schedule a task to run at any time or interval

Introduction

This is a simple class which can be used for scheduling a task to run at a specific time everyday or to run a task every interval. This can be used for any scheduled tasks like cleaning up files or any other resources, synchronize data to your application from any external data providers, optimize database at regular intervals, send bulk emails or other notifications like SMS in less bandwidth used hours (probably during night time), etc.

Background

I'm using .NET framework >=4.0 class Task in the solution. So check your project is compatible with this utility.

Using the Code

There are two kinds of task scheduling that are available:

public enum ScheduleKind
{
    // Scheduler which triggers at a specific time interval
    IntervalBased = 0,
    // Scheduler which runs at a specific time of everyday.
    TimeBased = 1
}

The main class of interest is the Scheduler class. This class inherits from System.Timers.Timer class and provides the task scheduling functionality.

// Used to schedule tasks to run on regular intervals or on specific time of everyday.
public class Scheduler : Timer, IDisposable
{
    private Scheduler() { }

    private TimeSpan _Time { get; set; }
    private ScheduleKind _Kind { get; set; }

    // Returns a new instance of timer and starts it
    // param name="Time": Interval time to execute the timer
    // param name="Trigger": Function to call in a new Thread when timer elapses, signal time is given as 
    //  input parameter to the function
    // param name="Kind": Specify scheduler type
    // returns: A System.Timers.Timer Instance
    public static Scheduler StartNew(TimeSpan Time, Action<datetime> Trigger,
        ScheduleKind Kind = ScheduleKind.IntervalBased)
    {
        Scheduler timer = MakeTimer(Time, Kind);
        timer.Elapsed += (s, e) => Task.Factory.StartNew(() => Trigger(e.SignalTime));
        return timer;
    }

    // Returns a new instance of timer and starts it
    // param name="Time": Interval time to execute the timer
    // param name="Trigger": Function to call in a new Thread when timer elapses, signal time is given as 
    //  input parameter to the function
    // param name="Kind": Specify scheduler type
    // param name="CallBackFn": Optional call back Action to execute after completing the Trigger function. 
    //  Input parameter of this Action is the result of Trigger function
    // returns: A System.Timers.Timer Instance
    public static Scheduler StartNew<t>(TimeSpan Time, Func<datetime> Trigger,
        ScheduleKind Kind = ScheduleKind.IntervalBased, Action<t> CallBackFn = null)
    {
        Scheduler timer = MakeTimer(Time, Kind);
        timer.Elapsed += (s, e) =>
        {
            if (CallBackFn != null)
            {
                Task.Factory.StartNew(() => Trigger(e.SignalTime))
                    .ContinueWith(prevTask => CallBackFn(prevTask.Result));
            }
            else
            {
                Task.Factory.StartNew(() => Trigger(e.SignalTime));
            }
        };
        return timer;
    }

    // Returns a new instance of timer and starts it
    // param name="Time">Interval time to execute the timer
    // param name="Trigger": Function to call in a new Thread when timer elapses, signal time is given as 
    //  input parameter to the function
    // param name="Kind": Specify scheduler type
    // param name="CallBackFn": Optional call back function to execute after completing the Trigger function. 
    //  Input parameter of this function is the result of Trigger function
    // returns: A System.Timers.Timer Instance
    public static Scheduler StartNew<t, v>(TimeSpan Time, Func<datetime> Trigger,
        ScheduleKind Kind = ScheduleKind.IntervalBased, Func<t, v> CallBackFn = null)
    {
        Scheduler timer = MakeTimer(Time, Kind);
        timer.Elapsed += (s, e) =>
        {
            if (CallBackFn != null)
            {
                Task.Factory.StartNew(() => Trigger(e.SignalTime))
                    .ContinueWith(prevTask => CallBackFn(prevTask.Result));
            }
            else
            {
                Task.Factory.StartNew(() => Trigger(e.SignalTime));
            }
        };
        return timer;
    }

    // Resets and restarts the scheduler
    public void Reset()
    {
        Stop();
        switch (_Kind)
        {
            case ScheduleKind.IntervalBased:
                Interval = _Time.TotalMilliseconds;
                break;
            case ScheduleKind.TimeBased:
                Interval = GetTimeDiff();
                break;
        }
        Enabled = true;
        Start();
    }

    // Creates a timer
    private static Scheduler MakeTimer(TimeSpan Time, ScheduleKind Kind = ScheduleKind.IntervalBased)
    {
        var timer = new Scheduler { _Time = Time, _Kind = Kind };
        timer.Reset();
        return timer;
    }

    // Returns TimeSpan difference of the next schedule time relative to current time
    private double GetTimeDiff()
    {
        try
        {
            // Scheduled time of today
            var nextRunOn =
                DateTime.Today.AddHours(_Time.Hours).AddMinutes(_Time.Minutes).AddSeconds(_Time.Seconds);
            if (nextRunOn < DateTime.Now)
            {
                nextRunOn = nextRunOn.AddMinutes(1);
            }
            if (nextRunOn < DateTime.Now) // If nextRunOn time is already past, set to next day
            {
                nextRunOn = nextRunOn.AddDays(1);
            }
            return (nextRunOn - DateTime.Now).TotalMilliseconds;
        }
        catch (Exception ex)
        {
            ex.WriteLog();
            return 24 * 60 * 60 * 1000;
        }
    }

    // Stop and dispose the timer
    protected override void Dispose(bool disposing)
    {
        Stop();
        base.Dispose(disposing);
    }
}

Using the Scheduler class is quite simple.

// A function that executes every 5 minutes
FiveMinScheduler = Scheduler.StartNew(TimeSpan.FromMinutes(5), 
_ => FiveMinScheduledFn()); // Runs on every 5 minutes

// A function that executes only once in a day at a specific time
NightScheduler = Scheduler.StartNew(TimeSpan.FromHours(2), NightScheduledFn, ScheduleKind.TimeBased); // Runs on 2AM everyday

// Using parameters in a schedule function
ParamerizedScheduler = Scheduler.StartNew(TimeSpan.FromDays(7), 
_ => ParamerizedScheduledFn(i, 6)); // Runs once in a week

// Using result of scheduled function in another callback function
CallbackScheduler = Scheduler.StartNew(TimeSpan.FromSeconds(30), _ => ParamerizedScheduledFn(i, 6),
    ScheduleKind.IntervalBased, CallBackFunc); // Runs on every 15 seconds

Here is some of the sample methods used in the above example which are passed to the Scheduler.StartNew() helper method.

internal void NightScheduledFn(DateTime initTime)
{
    Helper.WriteLog("I run at 2AM everyday. Current time is: " + DateTime.Now);
}

internal string ParamerizedScheduledFn(int i, int j)
{
    Helper.WriteLog(String.Format("Got parameters i={0} 
    and j={1}. Current time is: {2}", i, j, DateTime.Now));
    return (i*j).ToString(CultureInfo.InvariantCulture);
}

internal void CallBackFunc(string result)
{
    Helper.WriteLog(String.Format("Scheduled task finished on: {0}. 
    Result of scheduled task is: {1}", DateTime.Now, result));
}

To stop the Scheduler, call schedulerObject.Stop().

To restart the Scheduler, call schedulerObject.Reset().

Points of Interest

You can find a Windows service with self installer option with the attached source code.

Also checkout the behavioral change implementation using template pattern as suggested by John Brett.

Note: This is my first post on CodeProject. Please suggest ways to improve the tip.

License

This article, along with any associated source code and files, is licensed under The MIT License

Share

About the Author

Sen Jacob
Software Developer CCS Technologies
India India
I'm Sen Jacob. Find more info about me at StackOverflow Careers
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionSo many alternatives than reinventing the wheel... Pinmemberdevvvy9-Oct-14 17:24 
SuggestionBehaviour through OO rather than enums PinmemberJohn Brett11-Jun-14 2:31 
GeneralRe: Behaviour through OO rather than enums PinprofessionalSen Jacob11-Jun-14 5:40 
GeneralNicely written Pinmembershibin V.M11-Jun-14 0:58 
QuestionQuartz PinmemberOleg A.Lukin10-Jun-14 20:57 
AnswerRe: Quartz PinmvpSacha Barber10-Jun-14 23:36 
AnswerRe: Quartz PinprofessionalSen Jacob11-Jun-14 5:45 
AnswerRe: Quartz PinmemberMacSpudster17-Jun-14 6:37 
GeneralRe: T.Jefferson PinmemberOleg A.Lukin19-Jun-14 4:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 11 Jun 2014
Article Copyright 2014 by Sen Jacob
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid