view ServerMonitor/Objects/Schedule.cs @ 3:96f0b028176d

File check
author Brad Greco <brad@bgreco.net>
date Fri, 11 Jan 2019 22:34:18 -0500
parents 3e1a2131f897
children 3142e52cbe69
line wrap: on
line source

using System;

namespace ServerMonitorApp
{
    public class Schedule
    {
        public Schedule() { }

        public Schedule(FrequencyUnits units, int frequency, TimeSpan startTime, TimeSpan endTime)
        {
            Units = units;
            Frequency = frequency;
            StartTime = startTime;
            EndTime = endTime;
        }

        public int Frequency { get; set; }

        public FrequencyUnits Units { get; set; }

        public TimeSpan StartTime { get; set; }

        public TimeSpan EndTime { get; set; }

        public DateTime GetNextTime(DateTime lastScheduledTime)
        {
            return GetNextTime(lastScheduledTime, DateTime.Now);
        }

        public DateTime GetNextTime(DateTime lastScheduledTime, DateTime minStartTime)
        {
            DateTime nextTime = lastScheduledTime;
            if (Units == FrequencyUnits.Day)
            {
                //TODO what if nextTime is null or really long ago?
                while (nextTime < minStartTime)
                    nextTime = nextTime.AddDays(Frequency).Date.Add(StartTime);
            }
            else
            {
                // If the last run time was more than a day ago, fast-forward to reduce the number of loops
                if (nextTime < minStartTime.AddHours(-24))
                    nextTime = minStartTime.Date.Add(StartTime).AddHours(-24);
                //TODO handle start time and end time
                while (nextTime < minStartTime)
                {
                    switch (Units)
                    {
                        case FrequencyUnits.Second: nextTime = nextTime.AddSeconds(Frequency); break;
                        case FrequencyUnits.Minute: nextTime = nextTime.AddMinutes(Frequency); break;
                        case FrequencyUnits.Hour:   nextTime = nextTime.AddHours(Frequency);   break;
                        default: throw new InvalidOperationException("Unexpected frequency units: " + Units);
                    }
                }
                if (StartTime < EndTime)
                {
                    if (nextTime.TimeOfDay < StartTime)
                        nextTime = nextTime.Date + StartTime;
                    else if (nextTime.TimeOfDay > EndTime)
                        nextTime = nextTime.Date.AddDays(1) + StartTime;
                }
                else if (nextTime.TimeOfDay > EndTime && nextTime.TimeOfDay < StartTime)
                {
                    nextTime = nextTime.Date + StartTime;
                }
            }
            return nextTime;
        }
    }

    public enum FrequencyUnits { Second, Minute, Hour, Day }
}