Skip to content

Instantly share code, notes, and snippets.

@bluewalk
Last active November 2, 2020 12:27
Show Gist options
  • Save bluewalk/4c504b17318fee913ea912f14fcdcb4d to your computer and use it in GitHub Desktop.
Save bluewalk/4c504b17318fee913ea912f14fcdcb4d to your computer and use it in GitHub Desktop.
Simple C# class for task scheduling
/// <summary>
/// Task scheduler
/// </summary>
public class TaskScheduler
{
private readonly ILogger _logger;
private readonly List<Timer> _timers = new List<Timer>();
public TaskScheduler(ILogger<TaskScheduler> logger)
{
_logger = logger;
}
/// <summary>
/// Schedule task
/// </summary>
/// <param name="hour"></param>
/// <param name="min"></param>
/// <param name="interval"></param>
/// <param name="task"></param>
public void ScheduleTask(int hour, int min, TimeSpan interval, Action task)
{
_logger.LogInformation("Scheduling task {0}", task.Method.Name);
var now = DateTime.Now;
var firstRun = new DateTime(now.Year, now.Month, now.Day, hour, min, 0, 0);
while (now > firstRun)
firstRun = firstRun.AddSeconds(interval.TotalSeconds);
var timeToGo = firstRun - now;
if (timeToGo <= TimeSpan.Zero)
timeToGo = TimeSpan.Zero;
var timer = new Timer(x =>
{
_logger.LogInformation("Executing task {0}", task.Method.Name);
task.Invoke();
}, null, timeToGo, interval);
_timers.Add(timer);
}
/// <summary>
/// Clear scheduled tasks
/// </summary>
public void Clear()
{
_logger.LogInformation("Clearing tasks");
_timers.ForEach(t => t.Dispose());
_timers.Clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment