public class Scheduler : Timer
{
public delegate void ScheduleHandler();
private DateTime _When;
public DateTime When { get { return _When; } }
private TimeSpan _Interval = TimeSpan.FromDays(1.0);
public TimeSpan Interval { get { return _Interval; } }
private int _InternalCounter = 0;
private int _Count = 0;
public int Count { get { return _Count; } }
private ScheduleHandler _Handler;
public ScheduleHandler Handler { get { return _Handler; } }
public Scheduler(DateTime when, ScheduleHandler handler)
: this(when, TimeSpan.Zero, handler)
{ }
public Scheduler(DateTime when, TimeSpan interval, ScheduleHandler handler)
: this(when, interval, 0, handler)
{ }
public Scheduler(DateTime when, TimeSpan interval, int count, ScheduleHandler handler)
: base(TimeSpan.Zero, TimeSpan.FromMinutes(1.0), count)
{
Update(when.Year, when.Month, when.Day, when.Hour, when.Minute);
Update(interval);
Update(count);
Update(handler);
}
public void Update(int year, int month, int day, int hour, int minute)
{
if (year < DateTime.Now.Year)
{ year = DateTime.Now.Year; }
if (year > 9999)
{ year = 9999; }
if (month < 0)
{ month = 0; }
if (month > 11)
{ month = 11; }
if (day < 0)
{ day = 0; }
if (day > 31)
{ day = 31; }
if (hour < 0)
{ hour = 0; }
if (hour > 23)
{ hour = 23; }
if (minute < 0)
{ minute = 0; }
if (minute > 59)
{ minute = 59; }
_When = new DateTime(year, month, day, hour, minute, 0);
}
public void Update(TimeSpan interval)
{
if (interval.TotalMinutes < 1.0)
{ interval = TimeSpan.FromMinutes(1.0); }
_Interval = interval;
}
public void Update(int count)
{
if (count < 0)
{ count = 0; }
_InternalCounter = 0;
_Count = count;
}
public void Update(ScheduleHandler handler)
{
if (handler == null)
{ return; }
_Handler = handler;
}
public bool CheckHandle(DateTime now)
{
DateTime schedule = new DateTime(_When.Year, _When.Month, _When.Day, _When.Hour, _When.Minute, now.Second, now.Millisecond);
if (schedule == now)
{ return true; }
return false;
}
protected override void OnTick()
{
base.OnTick();
DateTime now = DateTime.Now;
if (CheckHandle(now))
{
_Handler.Invoke();
_InternalCounter++;
if (CanRepeat())
{
_When = _When.Add(_Interval);
if (!Running)
{ Start(); }
}
}
}
public virtual bool CanRepeat()
{ return (_Interval.TotalMinutes >= 1.0 && _Count == 0 || _InternalCounter < _Count); }
public override string ToString()
{ return String.Format("{0:D4}:{1:D2}:{2:D2}:{3:D2}:{4:D2}", _When.Year, _When.Month, _When.Day, _When.Hour, _When.Minute); }
}