Creating a simple task scheduler in C# that can execute tasks at a later time and in a sequential manner involves several steps. We'll implement a basic scheduler using a Queue to hold the tasks and a separate thread to process and execute these tasks when the time comes. For simplicity, tasks will be represented as Action objects, and each task will include a desired execution time.
Here's a basic implementation that you can expand and customize according to your needs:
Step 1: Define the Scheduler Class
First, let's create the primary class that will manage the task scheduling and execution.
using System;
using System.Collections.Generic;
using System.Threading;
public class TaskScheduler
{
private readonly object lockObject = new object();
private readonly Queue<(DateTime scheduledTime, Action task)> taskQueue = new();
private bool isRunning = true;
public TaskScheduler()
{
// Start the task processing thread
Thread thread = new Thread(ProcessTasks) { IsBackground = true };
thread.Start();
}
public void Stop()
{
isRunning = false;
}
public void ScheduleTask(DateTime scheduledTime, Action task)
{
lock (lockObject)
{
taskQueue.Enqueue((scheduledTime, task));
}
}
private void ProcessTasks()
{
while (isRunning)
{
(DateTime scheduledTime, Action task) taskToExecute = (DateTime.MaxValue, null);
lock (lockObject)
{
if (taskQueue.Count > 0 && taskQueue.Peek().scheduledTime <= DateTime.Now)
{
taskToExecute = taskQueue.Dequeue();
}
}
if (taskToExecute.task != null)
{
try
{
taskToExecute.task();
}
catch (Exception ex)
{
// Handle exceptions from the task
Console.WriteLine("Task Exception: " + ex.Message);
}
}
else
{
// No task to execute or tasks are not yet due, so sleep for a while
Thread.Sleep(1000); // Adjust the sleep time as needed
}
}
}
}
Step 2: Using the Task Scheduler
With the TaskScheduler class defined, you can now create tasks, schedule them, and let the scheduler handle their execution.
class Program
{
static void Main(string[] args)
{
TaskScheduler scheduler = new TaskScheduler();
// Schedule a task to run 5 seconds from now
scheduler.ScheduleTask(DateTime.Now.AddSeconds(5), () => Console.WriteLine("Task 1 executed at " + DateTime.Now));
// Schedule another task to run 10 seconds from now
scheduler.ScheduleTask(DateTime.Now.AddSeconds(10), () => Console.WriteLine("Task 2 executed at " + DateTime.Now));
Console.WriteLine("Tasks scheduled, press any key to exit.");
Console.ReadKey();
// Stop the scheduler gracefully before exiting
scheduler.Stop();
}
}
This simplistic task scheduler runs continuously, checking the queue for tasks due to run and executing them sequentially. The ProcessTasks method runs in a separate background thread to avoid blocking the main thread of your application.
Remarks
This implementation is quite basic and intended for educational purposes. It can be extended and improved in several ways, such as by handling task cancellation, improving the efficiency of the task checking loop, or supporting recurring tasks. In real-world applications, consider using existing robust solutions like Quartz.NET for advanced scheduling needs or leveraging built-in functionality like System.Threading.Timer for simpler cases.