Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A Task Scheduler Library for .NET Applications

0.00/5 (No votes)
10 Jun 2014 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here