Click here to Skip to main content
15,867,308 members
Articles / Desktop Programming / System
Tip/Trick

A Task Scheduler Library for .NET Applications

Rate me:
Please Sign up or sign in to vote.
4.90/5 (6 votes)
10 Jun 2014MIT1 min read 36.2K   604   27   11
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:

C#
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.

C#
// 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.

C#
// 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.

C#
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


Written By
Software Developer CCS Technologies
India India
I'm Sen Jacob. Find more info about me at StackOverflow Careers

Comments and Discussions

 
QuestionMonth Interval Pin
format C: /U29-Nov-15 4:47
format C: /U29-Nov-15 4:47 
QuestionSo many alternatives than reinventing the wheel... Pin
devvvy9-Oct-14 16:24
devvvy9-Oct-14 16:24 
AnswerRe: So many alternatives than reinventing the wheel... Pin
Sen Jacob22-Feb-15 8:15
professionalSen Jacob22-Feb-15 8:15 
SuggestionBehaviour through OO rather than enums Pin
John Brett11-Jun-14 1:31
John Brett11-Jun-14 1:31 
GeneralRe: Behaviour through OO rather than enums Pin
Sen Jacob11-Jun-14 4:40
professionalSen Jacob11-Jun-14 4:40 
GeneralNicely written Pin
shibin V.M10-Jun-14 23:58
shibin V.M10-Jun-14 23:58 
QuestionQuartz Pin
Oleg A.Lukin10-Jun-14 19:57
Oleg A.Lukin10-Jun-14 19:57 
AnswerRe: Quartz Pin
Sacha Barber10-Jun-14 22:36
Sacha Barber10-Jun-14 22:36 
AnswerRe: Quartz Pin
Sen Jacob11-Jun-14 4:45
professionalSen Jacob11-Jun-14 4:45 
AnswerRe: Quartz Pin
MacSpudster17-Jun-14 5:37
professionalMacSpudster17-Jun-14 5:37 
GeneralRe: T.Jefferson Pin
Oleg A.Lukin19-Jun-14 3:33
Oleg A.Lukin19-Jun-14 3:33 

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

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