Exemple #1
0
        public ScheduleInstant(DateTime nowInstant, TimeZoneInfo timeZone, [NotNull] CrontabSchedule schedule)
        {
            if (schedule == null) throw new ArgumentNullException("schedule");
            if (nowInstant.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", "nowInstant");
            }

            _timeZone = timeZone;
            _schedule = schedule;

            NowInstant = nowInstant.AddSeconds(-nowInstant.Second);

            var nextOccurrences = _schedule.GetNextOccurrences(
                TimeZoneInfo.ConvertTime(NowInstant, TimeZoneInfo.Utc, _timeZone),
                DateTime.MaxValue);

            foreach (var nextOccurrence in nextOccurrences)
            {
                if (_timeZone.IsInvalidTime(nextOccurrence)) continue;

                NextInstant = TimeZoneInfo.ConvertTime(nextOccurrence, _timeZone, TimeZoneInfo.Utc);
                break;
            }
        }
Exemple #2
0
        public ScheduleInstant(DateTime nowInstant, TimeZoneInfo timeZone, [NotNull] CrontabSchedule schedule)
        {
            if (schedule == null)
            {
                throw new ArgumentNullException("schedule");
            }
            if (nowInstant.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", "nowInstant");
            }

            _timeZone = timeZone;
            _schedule = schedule;

            NowInstant = nowInstant.AddSeconds(-nowInstant.Second);

            var nextOccurrences = _schedule.GetNextOccurrences(
                TimeZoneInfo.ConvertTime(NowInstant, TimeZoneInfo.Utc, _timeZone),
                DateTime.MaxValue);

            foreach (var nextOccurrence in nextOccurrences)
            {
                if (_timeZone.IsInvalidTime(nextOccurrence))
                {
                    continue;
                }

                NextInstant = TimeZoneInfo.ConvertTime(nextOccurrence, _timeZone, TimeZoneInfo.Utc);
                break;
            }
        }
Exemple #3
0
        public ScheduledJobRunner(Func <IJob> jobFactory, string schedule, ICacheClient cacheClient, ILoggerFactory loggerFactory = null)
        {
            _jobFactory = jobFactory;
            Schedule    = schedule;
            _logger     = loggerFactory?.CreateLogger <ScheduledJobRunner>() ?? NullLogger <ScheduledJobRunner> .Instance;

            _runner = new JobRunner(jobFactory, loggerFactory, runContinuous: false);

            _cronSchedule = CrontabSchedule.TryParse(schedule, s => s, e => {
                var ex = e();
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError(ex, "Error parsing schedule {Schedule}: {Message}", schedule, ex.Message);
                }
                return(null);
            });

            if (_cronSchedule == null)
            {
                throw new ArgumentException("Could not parse schedule.", nameof(schedule));
            }

            var dates    = _cronSchedule.GetNextOccurrences(SystemClock.UtcNow, DateTime.MaxValue).Take(2).ToList();
            var interval = TimeSpan.FromDays(1);

            if (dates.Count == 2)
            {
                interval = dates[1].Subtract(dates[0]);
            }

            _lockProvider = new ThrottlingLockProvider(cacheClient, 1, interval.Add(interval));
        }
Exemple #4
0
        public ScheduleInstant(DateTime nowInstant, TimeZoneInfo timeZone, [NotNull] CrontabSchedule schedule, DateTime?endDate = null)
        {
            if (schedule == null)
            {
                throw new ArgumentNullException(nameof(schedule));
            }
            if (nowInstant.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", nameof(nowInstant));
            }

            _timeZone = timeZone;
            _schedule = schedule;

            NowInstant = nowInstant.AddSeconds(-nowInstant.Second);

            var occurenceEndDate = endDate ?? DateTime.MaxValue;

            var nextOccurrences = _schedule.GetNextOccurrences(TimeZoneInfo.ConvertTime(NowInstant, TimeZoneInfo.Utc, _timeZone), occurenceEndDate)
                                  .Where(x => x != occurenceEndDate); // Explicitly exclude the end date

            foreach (var nextOccurrence in nextOccurrences)
            {
                if (_timeZone.IsInvalidTime(nextOccurrence))
                {
                    continue;
                }

                NextInstant = TimeZoneInfo.ConvertTime(nextOccurrence, _timeZone, TimeZoneInfo.Utc);
                break;
            }
        }
        /// <inheritdoc />
        public IEnumerable <DateTime> GetNextOccurrences(DateTime baseTime, DateTime endTime)
        {
            DateTime adjustedBaseTime = AdjustDateTime(baseTime);
            DateTime adjustedEndTime  = AdjustDateTime(endTime);

            return(crontabSchedule
                   .GetNextOccurrences(adjustedBaseTime, adjustedEndTime)
                   .Select(AdjustOccurrence));
        }
Exemple #6
0
        public IEnumerable <DateTime> GetMatches(DateTime?lastMachingTime)
        {
            if (lastMachingTime.HasValue && lastMachingTime.Value.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", "lastMachingTime");
            }

            var baseTime = lastMachingTime ?? UtcTime.AddSeconds(-1);
            var endTime  = UtcTime.AddSeconds(1);

            return(_schedule.GetNextOccurrences(baseTime, endTime));
        }
Exemple #7
0
        public static DateTime GetLastScheduledOccurence(this CrontabSchedule schedule, DateTime dateTime)
        {
            var occurences = schedule.GetNextOccurrences(dateTime, DateTime.MaxValue)
                             .Cast <DateTime?>()
                             .Prepend(default(DateTime?))
                             .Pairwise((prev, curr) => new { Previous = prev, Current = curr }).Take(5);
            var occurence = occurences.Skip(1).Take(1).Single();
            var timespan  = occurence.Current - occurence.Previous;

            DateTime lastOccurrence = (occurence.Previous ?? DateTime.MinValue) - (timespan ?? TimeSpan.FromSeconds(0));

            return(lastOccurrence);
        }
        private IEnumerable <DateTimeOffset> GetFiniteSeriesOccurrences(DateTimeOffset end)
        {
            CrontabSchedule schedule = TryParseCron();

            if (schedule == null)
            {
                return(Enumerable.Empty <DateTimeOffset>());
            }

            IEnumerable <DateTime>       nextOccurrences = schedule.GetNextOccurrences(RunAt.UtcDateTime, end.UtcDateTime);
            IEnumerable <DateTimeOffset> occurrences     = nextOccurrences.Select(o => new DateTimeOffset(o));

            return(occurrences);
        }
Exemple #9
0
        public IEnumerable <DateTime> GetNextInstants(DateTime lastInstant)
        {
            if (lastInstant.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", nameof(lastInstant));
            }

            return(_schedule
                   .GetNextOccurrences(
                       TimeZoneInfo.ConvertTime(lastInstant, TimeZoneInfo.Utc, _timeZone),
                       TimeZoneInfo.ConvertTime(NowInstant.AddSeconds(1), TimeZoneInfo.Utc, _timeZone))
                   .Where(x => !_timeZone.IsInvalidTime(x))
                   .Select(x => TimeZoneInfo.ConvertTime(x, _timeZone, TimeZoneInfo.Utc))
                   .ToList());
        }
        private static bool Test(this CrontabSchedule schedule, Booking booking, DateTime start, DateTime end, IList <Booking> bookings, out IList <DateTime> availableMinutes)
        {
            if (bookings == null)
            {
                bookings = new Booking[0];
            }

            availableMinutes = schedule.GetNextOccurrences(start.AddMinutes(-1), end).Where(d =>
            {
                return(d >= booking.Start && d < booking.End);
            }).ToList();
            var isAvailable = availableMinutes.Count() == booking.Duration.TotalMinutes;

            Console.WriteLine($"{availableMinutes.Count()}/{booking.Duration.TotalMinutes} available in [{schedule}]");
            return(isAvailable);
        }
Exemple #11
0
        public IEnumerable <DateTime> GetNextInstants(DateTime?lastInstant)
        {
            if (lastInstant.HasValue && lastInstant.Value.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", "lastInstant");
            }

            var baseTime = lastInstant ?? NowInstant.AddSeconds(-1);
            var endTime  = NowInstant.AddSeconds(1);

            return(_schedule
                   .GetNextOccurrences(
                       TimeZoneInfo.ConvertTimeFromUtc(baseTime, _timeZone),
                       TimeZoneInfo.ConvertTimeFromUtc(endTime, _timeZone))
                   .Select(x => TimeZoneInfo.ConvertTimeToUtc(x, _timeZone))
                   .ToList());
        }
Exemple #12
0
            // Only the Excel thread should touch m_Timer.Enabled. If a pool thread can flip the
            // state of Enabled we may get race conditions with timers being inadvertently
            // re-enabled after being switched off.

            public CronTimer(String ckey, String cronex, DateTime?start, DateTime?end)
            {
                // Save setup parms so later invocations of AddCron can check whether we need
                // to create a new instance or not.
                m_Key    = ckey;
                m_Cronex = cronex;
                m_Start  = start;
                m_End    = end;
                // Now do the real biz of setting up the timer.
                DateTime        sStart   = start ?? DateTime.Now;
                DateTime        sEnd     = end ?? new DateTime(sStart.Year, sStart.Month, sStart.Day, 23, 59, 59);
                CrontabSchedule schedule = CrontabSchedule.Parse(cronex);

                m_Schedule        = schedule.GetNextOccurrences(sStart, sEnd);
                m_Iterator        = m_Schedule.GetEnumerator( );
                m_Timer           = new System.Timers.Timer( );
                m_Timer.Enabled   = false;
                m_Timer.AutoReset = false;
                m_Timer.Elapsed  += this.OnTimerEvent;
                ScheduleTimer( );
                m_Timer.Enabled = true;
            }
Exemple #13
0
        void DoCrontabbing()
        {
            _resultBox.Clear();
            _errorProvider.SetError(_cronBox, null);
            _statusBarPanel.Text = "Ready";
            _moreButton.Enabled  = false;

            if (_crontab == null)
            {
                try
                {
                    var expression = _cronBox.Text.Trim();

                    if (expression.Length == 0)
                    {
                        return;
                    }

                    _isSixPart = expression.Split(Separators, StringSplitOptions.RemoveEmptyEntries).Length == 6;
                    _crontab   = CrontabSchedule.Parse(expression, new CrontabSchedule.ParseOptions {
                        IncludingSeconds = _isSixPart
                    });

                    _totalOccurrenceCount = 0;

                    _startTime = DateTime.ParseExact(_startTimePicker.Text,
                                                     _startTimePicker.CustomFormat, CultureInfo.InvariantCulture,
                                                     DateTimeStyles.AssumeLocal) - (_isSixPart ? TimeSpan.FromSeconds(1): TimeSpan.FromMinutes(1));
                }
                catch (CrontabException e)
                {
                    _errorProvider.SetError(_cronBox, e.Message);

                    var traceBuilder = new StringBuilder();

                    Exception traceException = e;
                    Exception lastException;

                    do
                    {
                        traceBuilder.Append(traceException.Message);
                        traceBuilder.Append("\r\n");
                        lastException  = traceException;
                        traceException = traceException.GetBaseException();
                    }while (lastException != traceException);

                    _resultBox.Text = traceBuilder.ToString();
                    return;
                }
            }

            var endTime = DateTime.ParseExact(_endTimePicker.Text,
                                              _endTimePicker.CustomFormat, CultureInfo.InvariantCulture,
                                              DateTimeStyles.AssumeLocal);

            var sb = new StringBuilder();

            var       count          = 0;
            const int maxCount       = 500;
            var       info           = DateTimeFormatInfo.CurrentInfo;
            var       dayWidth       = info.AbbreviatedDayNames.Max(s => s.Length);
            var       monthWidth     = info.AbbreviatedMonthNames.Max(s => s.Length);
            var       timeComponent  = _isSixPart ? "HH:mm:ss" : "HH:mm";
            var       timeFormat     = $"{{0,-{dayWidth}:ddd}} {{0:dd}}, {{0,-{monthWidth}:MMM}} {{0:yyyy {timeComponent}}}";
            var       lastTimeString = new string('?', string.Format(timeFormat, DateTime.MinValue).Length);

            foreach (var occurrence in _crontab.GetNextOccurrences(_startTime, endTime))
            {
                if (count + 1 > maxCount)
                {
                    break;
                }

                _startTime = occurrence;
                _totalOccurrenceCount++;
                count++;

                var timeString = string.Format(timeFormat, occurrence);

                sb.Append(timeString);
                sb.Append(" | ");

                var index = Diff(lastTimeString, timeString, 0, dayWidth, sb);
                sb.Append(' ');
                index = Diff(lastTimeString, timeString, index + 1, 2, sb);
                sb.Append(", ");
                index = Diff(lastTimeString, timeString, index + 2, monthWidth, sb);
                sb.Append(' ');
                index = Diff(lastTimeString, timeString, index + 1, 4, sb);
                sb.Append(' ');
                index = Diff(lastTimeString, timeString, index + 1, 2, sb);
                sb.Append(':');
                index = Diff(lastTimeString, timeString, index + 1, 2, sb);
                if (_isSixPart)
                {
                    sb.Append(':');
                    Diff(lastTimeString, timeString, index + 1, 2, sb);
                }

                lastTimeString = timeString;

                sb.Append("\r\n");
            }

            _moreButton.Enabled = count == maxCount;

            _statusBarPanel.Text = $"Last count = {count:N0}, Total = {_totalOccurrenceCount:N0}";

            _resultBox.Text = sb.ToString();
            _resultBox.Select(0, 0);
            _resultBox.ScrollToCaret();
        }
Exemple #14
0
        private void SetUpTimer(ModuleConfiguration moduleConfiguration)
        {
            if (string.IsNullOrEmpty(moduleConfiguration.CronTime))
            {
                return;
            }

            CrontabSchedule        s           = CrontabSchedule.Parse(moduleConfiguration.CronTime);
            DateTime               start       = DateTime.Now;
            DateTime               end         = start.AddDays(1);
            IEnumerable <DateTime> occurrences = s.GetNextOccurrences(start, end);

            if (cron2Timers.ContainsKey(moduleConfiguration.CronTime))
            {
                cron2Timers.Remove(moduleConfiguration.CronTime);
            }

            List <Timer> timers = new List <Timer>();

            cron2Timers.Add(moduleConfiguration.CronTime, timers);

            foreach (DateTime startTime in occurrences)
            {
                DateTime current   = DateTime.Now;
                TimeSpan alertTime = new TimeSpan(startTime.Hour, startTime.Minute, startTime.Second);
                TimeSpan timeToGo  = alertTime - current.TimeOfDay;

                if (timeToGo < TimeSpan.Zero)
                {
                    timeToGo = timeToGo.Add(new TimeSpan(1, 0, 0, 0));
                }

                Timer moduleTimer = new Timer(x =>
                {
                    try
                    {
                        lastModule.Pausing = true;
                        ModuleBase module  = GetModuleBase(moduleConfiguration);

                        while (module.IsRunning)
                        {
                            Thread.Sleep(_frameRate);
                            module.Start(processor);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                    }
                    finally
                    {
                        timers.Remove(timers.First());

                        if (!timers.Any())
                        {
                            SetUpTimer(moduleConfiguration);
                        }

                        lastModule.Pausing = false;
                    }
                }, null, timeToGo, Timeout.InfiniteTimeSpan);

                timers.Add(moduleTimer);
            }
        }