/// <summary>
 /// Constructs a new instance based on the specified crontab expression
 /// </summary>
 /// <param name="cronTabExpression">The crontab expression defining the schedule</param>
 public CronSchedule(string cronTabExpression)
 {
     CrontabSchedule.ParseOptions options = new CrontabSchedule.ParseOptions()
     {
         IncludingSeconds = true
     };
     _cronSchedule = CrontabSchedule.Parse(cronTabExpression, options);
 }
Exemplo n.º 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;
            }
        }
Exemplo n.º 3
0
 // ReSharper disable once InconsistentNaming
 void CronBox_Changed(object sender, EventArgs args)
 {
     _lastChangeTime = DateTime.Now;
     _dirty = true;
     _isSixPart = false;
     _crontab = null;
 }
Exemplo n.º 4
0
        public IScheduleInstant GetInstant(CrontabSchedule schedule, TimeZoneInfo timeZone)
        {
            if (schedule == null) throw new ArgumentNullException("schedule");
            if (timeZone == null) throw new ArgumentNullException("timeZone");

            return new ScheduleInstant(DateTime.UtcNow, timeZone, schedule);
        }
Exemplo n.º 5
0
        public Task GoLiveHangfire(LiveSermonsSchedulingRequest request)
        {
            var jobId = request.StartSchedule;

            CrontabSchedule schedule = CrontabSchedule.Parse(request.EndSchedule);
            DateTime        endTime  = schedule.GetNextOccurrence(DateTime.Now);

            var liveStreamUpdate = new LiveSermonsUpdateRequest
            {
                ExpirationTime = endTime
            };

            return(GoLive(liveStreamUpdate));
        }
Exemplo n.º 6
0
        public ScheduleInstant(DateTime utcTime, [NotNull] CrontabSchedule schedule)
        {
            if (utcTime.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Only DateTime values in UTC should be passed.", "utcTime");
            }

            if (schedule == null) throw new ArgumentNullException("schedule");

            _schedule = schedule;

            UtcTime = utcTime;
            NextOccurrence = _schedule.GetNextOccurrence(UtcTime);
        }
Exemplo n.º 7
0
        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);
        }
Exemplo n.º 8
0
        private DateTimeOffset?GetNextOccurrenceInInfiniteSeries()
        {
            CrontabSchedule schedule = TryParseCron();

            if (schedule == null)
            {
                return(null);
            }

            // IMPORTANT: DateTimeOffset.DateTime will produce a time with Kind == Unspecified, do not use!
            DateTime nextOccurrence = schedule.GetNextOccurrence(RunAt.UtcDateTime);

            return(new DateTimeOffset(nextOccurrence));
        }
Exemplo n.º 9
0
        private async Task ScheduledTask(CancellationToken ct)
        {
            if (CronSchedules == null || CronSchedules.Length == 0)
            {
                var cronSchedule = (CronJobAttribute)typeof(TService).GetCustomAttributes(typeof(CronJobAttribute), true).FirstOrDefault();
                if (cronSchedule != null)
                {
                    CronSchedules = cronSchedule.Schedules;
                }
            }

            if (CronSchedules == null || CronSchedules.Length == 0)
            {
                throw new Exception("Job must pass cron schedules or have a CronJobAttribute");
            }

            var schedules = CronSchedules.Select(schedule => CrontabSchedule.Parse(schedule));

            do
            {
                var currentTime   = DateTime.UtcNow;
                var nextOccurence = schedules.Select(schedule => schedule.GetNextOccurrence(currentTime)).Min();

                var delay = nextOccurence - currentTime;
                if (delay.Seconds > 0)
                {
                    await Task.Delay(delay);
                }

                //Unit of Work
                using (var scope = _services.CreateScope())
                {
                    var scopedProcessingService =
                        scope.ServiceProvider
                        .GetRequiredService <TService>();

                    _logger.LogInformation("Executing CronJob {CronJob}", typeof(TService));
                    try
                    {
                        await scopedProcessingService.ExecuteAsync(ct);

                        _logger.LogInformation("CronJob {CronJob} completed successfully", typeof(TService));
                    }
                    catch
                    {
                        _logger.LogInformation("CronJob {CronJob} failed", typeof(TService));
                    }
                }
            }while (!ct.IsCancellationRequested);
        }
Exemplo n.º 10
0
 private void ValidateCrontab(string crontab)
 {
     try
     {
         var schedule = CrontabSchedule.Parse(crontab, new CrontabSchedule.ParseOptions {
             IncludingSeconds = true
         });
         schedule.GetNextOccurrence(DateTime.UtcNow);
     }
     catch (Exception ex)
     {
         throw new Exception("Crontab is invalid. See the inner exception for details.", ex);
     }
 }
 public void UpdateAccessTokenCleanupCronJob(string accessTokenCleanupCronJob, bool shouldValueFallback)
 {
     try
     {
         CleanupJobSchedule = CrontabSchedule.Parse(accessTokenCleanupCronJob);
     }
     catch
     {
         if (!shouldValueFallback)
         {
             throw;
         }
     }
 }
Exemplo n.º 12
0
        /// <summary>
        ///     Remove all expired identity token
        /// </summary>
        /// <param name="identityServerBuilder"></param>
        /// <param name="accessTokenCleanerCronJob"></param>
        public static IIdentityServerBuilder AddExpiredAccessTokenCleaner(this IIdentityServerBuilder identityServerBuilder, string accessTokenCleanerCronJob = default)
        {
            identityServerBuilder.Services.AddHostedService <ExpiredTokenCleanUpHostedService>();

            var authenticationAdapterSettings = new AuthenticationAdapterSettings();

            if (!string.IsNullOrWhiteSpace(accessTokenCleanerCronJob) && CrontabSchedule.TryParse(accessTokenCleanerCronJob) != null)
            {
                authenticationAdapterSettings.UpdateAccessTokenCleanupCronJob(accessTokenCleanerCronJob, true);
            }
            identityServerBuilder.Services.AddSingleton(authenticationAdapterSettings);

            return(identityServerBuilder);
        }
Exemplo n.º 13
0
        public void AddTask(IScheduledTask task)
        {
            if (!_scheduledTasks.ContainsKey(task.Id))
            {
                _scheduledTasks.Add(task.Id, new SchedulerTaskWrapper
                {
                    Schedule    = CrontabSchedule.Parse(task.Schedule),
                    Task        = task,
                    NextRunTime = task.NextRunTime
                });

                _logger.LogInformation($"Scheduler added task: {task.Name} | {task.Schedule}");
            }
        }
Exemplo n.º 14
0
        public DateTimeOffset GetNewNextRun()
        {
            var now        = DateTime.UtcNow;
            var currentRun = NextRun ?? now;

            if (!IsAlive())
            {
                return(currentRun);
            }

            return(CrontabSchedule
                   .Parse(Definition.Cron)
                   .GetNextOccurrence(currentRun.UtcDateTime));
        }
Exemplo n.º 15
0
        public SchedulerHostedService(IEnumerable <IScheduledTask> scheduledTasks)
        {
            var referenceTime = DateTime.UtcNow + TimeSpan.Parse("07:00:00") + TimeSpan.Parse("00:00:20");

            foreach (var scheduledTask in scheduledTasks)
            {
                _scheduledTasks.Add(new SchedulerTaskWrapper
                {
                    Schedule    = CrontabSchedule.Parse(scheduledTask.Schedule),
                    Task        = scheduledTask,
                    NextRunTime = CrontabSchedule.Parse(scheduledTask.Schedule).GetNextOccurrence(referenceTime)
                });
            }
        }
Exemplo n.º 16
0
 public SchedulerHostedService(IEnumerable <IScheduledTask> scheduledTasks)
 {
     foreach (var scheduledTask in scheduledTasks)
     {
         var schedule = CrontabSchedule.Parse(scheduledTask.Schedule);
         var nextRun  = schedule.GetNextOccurrence(DateTime.Now);
         _scheduledTasks.Add(new SchedulerTaskWrapper
         {
             Schedule    = schedule,
             Task        = scheduledTask,
             NextRunTime = nextRun
         });
     }
 }
        public SchedulerService(IEnumerable <IScheduledTask> tasks)
        {
            var utcNow = DateTime.UtcNow;

            foreach (var scheduledTask in tasks)
            {
                _tasks.Add(new SchedulerTask
                {
                    Schedule       = CrontabSchedule.Parse(scheduledTask.Schedule),
                    Task           = scheduledTask,
                    NextRunTimeUtc = utcNow
                });
            }
        }
Exemplo n.º 18
0
        public string getstatus()
        {
            System.Timers.Timer t = new System.Timers.Timer();
            var      schedule_    = CrontabSchedule.Parse(schedule);
            DateTime _nextRun     = schedule_.GetNextOccurrence(DateTime.Now);
            DateTime __nextRun    = schedule_.GetNextOccurrence(_nextRun);
            TimeSpan span         = __nextRun.Subtract(_nextRun);

            t.Interval = span.TotalMilliseconds;
            t.Elapsed += T_Elapsed;
            t.Start();

            return(status);
        }
        public SchedulerHostedService(IEnumerable <IScheduledTask> scheduledTasks)
        {
            var referenceTime = DateTime.UtcNow;

            foreach (var scheduledTask in scheduledTasks)
            {
                _scheduledTasks.Add(new SchedulerTaskWrapper
                {
                    Schedule    = CrontabSchedule.Parse(scheduledTask.Schedule),
                    Task        = scheduledTask,
                    NextRunTime = referenceTime
                });
            }
        }
Exemplo n.º 20
0
        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            var firedtimer = (from tmpTimer in currentAlertsTimers
                              where tmpTimer.Value.Equals(source)
                              select tmpTimer).FirstOrDefault();

            if (firedtimer.Key == null)
            {
                if (Cron.verbose)
                {
                    Console.WriteLine("The Elapsed event was raised at {0}:{1}\n{2}", e.SignalTime, firedtimer.Key, "null");
                }
            }
            else
            {
                if (Cron.verbose)
                {
                    Console.WriteLine("The scheduled event at {0}\n{1}:{2}", e.SignalTime, firedtimer.Key, commandLines[firedtimer.Key].Command);
                }
                string   command   = commandLines[firedtimer.Key].Command;
                string   options   = commandLines[firedtimer.Key].IntervalOptions;
                DateTime startDate = DateTime.Now;
                DateTime endDate   = DateTime.Now.AddYears(1);
                DateTime futureEvent;
                double   interval;
                IEnumerable <DateTime> occurrence;

                Console.Write("[TCron]->");
                Commands.HandleCommand(TSPlayer.Server, (command.StartsWith("/") ? command : "/" + command));
                var schedule = CrontabSchedule.Parse(options);
                startDate  = DateTime.Now;
                occurrence = schedule.GetNextOccurrences(startDate, endDate);

                /*
                 *              {
                 *                  int count = 0;
                 *                  foreach (var o in schedule.GetNextOccurrences(startDate, endDate))
                 *                  {
                 *                      if (count++ > 3)
                 *                          break;
                 *                      Console.WriteLine(">" + o);
                 *                  }
                 *              }
                 */
                futureEvent = occurrence.FirstOrDefault();
                interval    = (futureEvent - startDate).TotalMilliseconds;
                firedtimer.Value.Interval = interval;
            }
        }
Exemplo n.º 21
0
        void ReadAndParseFile()
        {
            _logger.Info("Parsing cron.txt file...");
            _cronList = new List <CronJob>();

            foreach (var line in File.ReadAllLines(_file.FullName))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var str = line.Trim();
                if (str.StartsWith("#"))
                {
                    continue;
                }

                var arr = str.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                if (arr.Length < 2)
                {
                    continue;
                }

                var cronstr = arr[0].Trim();
                var cmdstr  = arr[1].Trim();
                var cmdarr  = Regex.Replace(cmdstr, @"\s+", " ").Split(' ');
                var cmd     = cmdarr.First();
                var args    = cmdarr.Skip(1).ToArray();

                CrontabSchedule schedule;
                try
                {
                    schedule = CrontabSchedule.Parse(arr[0].Trim());
                    if (schedule == null)
                    {
                        continue;
                    }
                }
                catch
                {
                    continue;
                }

                _cronList.Add(new CronJob(schedule, cronstr, cmd, args));
            }
            _logger.Info("Found {0} cron job(s) - {1}", _cronList.Count, DateTime.Now);
            _logger.Info("Cron job list successfully updated from config file.");
        }
Exemplo n.º 22
0
        public SchedulerHostedService(IEnumerable <IScheduledTask> scheduledTasks)
        {
            var referenceTime = DateTime.Now;

            foreach (var scheduledTask in scheduledTasks)
            {
                Console.WriteLine("Adding task" + scheduledTask.ToString());
                _scheduledTasks.Add(new SchedulerTaskWrapper
                {
                    Schedule    = CrontabSchedule.Parse(scheduledTask.Schedule),
                    Task        = scheduledTask,
                    NextRunTime = referenceTime
                });
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Gets the full description of the cron tab schedule
        /// </summary>
        /// <param name="crontab">The crontab.</param>
        /// <returns></returns>
        public static string GetFullDescription(string crontab)
        {
            if (crontab != null)
            {
                var ncrontab = CrontabSchedule.TryParse(crontab);
                if (ncrontab == null)
                {
                    return(string.Empty);
                }

                return(BuildDescription(ncrontab));
            }

            return(string.Empty);
        }
Exemplo n.º 24
0
        public void Formatting()
        {
            Assert.AreEqual("* 1-3 * * *", CrontabSchedule.Parse("* 1-2,3 * * *").ToString());
            Assert.AreEqual("* * * 1,3,5,7,9,11 *", CrontabSchedule.Parse("* * * */2 *").ToString());
            Assert.AreEqual("10,25,40 * * * *", CrontabSchedule.Parse("10-40/15 * * * *").ToString());
            Assert.AreEqual("* * * 1,3,8 1-2,5", CrontabSchedule.Parse("* * * Mar,Jan,Aug Fri,Mon-Tue").ToString());
            var includingSeconds = new ParseOptions {
                IncludingSeconds = true
            };

            Assert.AreEqual("1 * 1-3 * * *", CrontabSchedule.Parse("1 * 1-2,3 * * *", includingSeconds).ToString());
            Assert.AreEqual("22 * * * 1,3,5,7,9,11 *", CrontabSchedule.Parse("22 * * * */2 *", includingSeconds).ToString());
            Assert.AreEqual("33 10,25,40 * * * *", CrontabSchedule.Parse("33 10-40/15 * * * *", includingSeconds).ToString());
            Assert.AreEqual("55 * * * 1,3,8 1-2,5", CrontabSchedule.Parse("55 * * * Mar,Jan,Aug Fri,Mon-Tue", includingSeconds).ToString());
        }
Exemplo n.º 25
0
        public async Task EndLiveHangfire(LiveSermonsSchedulingRequest request)
        {
            CrontabSchedule schedule  = CrontabSchedule.Parse(request.StartSchedule);
            DateTime        nextLocal = schedule.GetNextOccurrence(DateTime.Now);

            List <RecurringJobDto> recurringJobs = JobStorage.Current.GetConnection().GetRecurringJobs();
            var nextJobExecTime = recurringJobs.OrderBy(i => i.NextExecution.Value).First().NextExecution.Value;

            // make sure that we're using UTC
            DateTime nextLive = nextJobExecTime.ToUniversalTime();

            var liveStreamCompletedResponse = await _sermonsRepository.UpdateLiveSermonsInactive(nextLive);

            return;
        }
Exemplo n.º 26
0
        public void NextInstant_DoesntThrow_NearDaylightSavings()
        {
            // Arrange
            _timeZone = GetNewYorkTimeZone();
            _now = TimeZoneInfo.ConvertTime(new DateTime(2016, 3, 13, 1, 0, 0), _timeZone, TimeZoneInfo.Utc);
            _schedule = CrontabSchedule.Parse("0 * * * *");
            
            var instant = CreateInstant();

            // Act
            var value = instant.NextInstant;

            // Assert
            Assert.Equal(_now.AddHours(1), value);
        }
Exemplo n.º 27
0
        public SchedulerHostedService(IEnumerable <IScheduledTask> scheduledTasks)
        {
            var referenceTime = DateTime.UtcNow;

            foreach (var scheduledTask in scheduledTasks)
            {
                _scheduledTasks.Add(new SchedulerTaskWrapper
                {
                    Schedule    = CrontabSchedule.Parse(scheduledTask.Schedule),
                    interval    = TimeSpan.FromSeconds(scheduledTask.exicuteEverySeconds),
                    Task        = scheduledTask,
                    NextRunTime = referenceTime
                });
            }
        }
Exemplo n.º 28
0
        public void NextInstant_DoesntThrow_NearDaylightSavings()
        {
            // Arrange
            _timeZone = GetNewYorkTimeZone();
            _now      = TimeZoneInfo.ConvertTimeToUtc(new DateTime(2016, 3, 13, 1, 0, 0), _timeZone);
            _schedule = CrontabSchedule.Parse("0 * * * *");

            var instant = CreateInstant();

            // Act
            var value = instant.NextInstant;

            // Assert
            Assert.Equal(_now.AddHours(1), value);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Generic crontab runner
 /// </summary>
 /// <param name="wrokerAction"></param>
 /// <param name="workerEnabled"></param>
 /// <param name="workerCronTab"></param>
 /// <param name="workerNextOccurence"></param>
 private void DoCrontabRunner(Action wrokerAction, bool workerEnabled, string workerCronTab, ref DateTime workerNextOccurence)
 {
     if (workerEnabled)
     {
         if (workerNextOccurence < DateTime.Now || workerNextOccurence == null)
         {
             CrontabSchedule c = CrontabSchedule.Parse(workerCronTab);
             workerNextOccurence = c.GetNextOccurrence(DateTime.Now, DateTime.Now.AddYears(1));
             if (runactions)
             {
                 wrokerAction();
             }
         }
     }
 }
Exemplo n.º 30
0
        public static IObservable <int> Cron(string cron, IScheduler scheduler)
        {
            var schedule = CrontabSchedule.Parse(cron);

            return(Observable.Generate(
                       0,
                       d => true,
                       d => d + 1,
                       d => d,
                       timeSelector: d =>
            {
                return new DateTimeOffset(schedule.GetNextOccurrence(scheduler.Now.DateTime));
            },
                       scheduler: scheduler));
        }
Exemplo n.º 31
0
 private pollWrapper EnsureWrapped(PollingSchedule item)
 {
     if (!pollingControl.ContainsKey(item.Url))
     {
         var pw = new pollWrapper
         {
             Schedule = CrontabSchedule.Parse(item.Schedule) //,
                                                             //LastRunTime = DateTime.MinValue,
                                                             //NextRunTime = DateTime.MinValue
         };
         pw.NextRunTime = pw.Schedule.GetNextOccurrence(DateTime.Now);
         pollingControl.Add(item.Url, pw);
     }
     return(pollingControl[item.Url]);
 }
Exemplo n.º 32
0
        private static TimeSpan CompareTwoCronOccurrences(CrontabSchedule schedule)
        {
            var now = DateTime.Now;             // <-- throw this one away to normalize

            now = new DateTime(now.AddMonths(1).Year, now.AddMonths(1).Month,
                               1);  // <-- advance to next month to catch off-by-one errors

            var from = schedule.GetNextOccurrence(now);

            from = schedule.GetNextOccurrence(from);
            var to   = schedule.GetNextOccurrence(from);
            var diff = to - from;

            return(diff);
        }
        private void SchedulePlugin(IDataPlugin plugin, CancellationToken cancellationToken)
        {
            var schedule = CrontabSchedule.Parse(plugin.CronSchedule, new CrontabSchedule.ParseOptions {
                IncludingSeconds = true
            });
            DateTimeOffset nextOccurrence = schedule.GetNextOccurrence(_dateTimeProvider.Now.DateTime);

            _logger.LogDebug($"{plugin.TileId.TileType} plugin: \"{plugin.TileId.TileName}\" - Next schedule {nextOccurrence}");
            Observable.Timer(nextOccurrence)
            .Select(x => HandlePlugin(plugin, cancellationToken))
            .Switch()
            .Subscribe(
                plugin => SchedulePlugin(plugin, cancellationToken),
                exception => _logger.LogError($"Error occurs during plugin processing. Plugin will be disabled. Error: {exception.Message}. Inner Exception: {exception.InnerException?.Message}", exception));
        }
Exemplo n.º 34
0
        public Task GetNextCronExpressionOccurrence()
        {
            var             expression = GetQueryStringValueAndAssertIfSingleAndNotEmpty("expression");
            CrontabSchedule crontabSchedule;

            try
            {
                // will throw if the cron expression is invalid
                crontabSchedule = CrontabSchedule.Parse(expression);
            }
            catch (Exception e)
            {
                using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                    using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyName(nameof(NextCronExpressionOccurrence.IsValid));
                        writer.WriteBool(false);
                        writer.WriteComma();
                        writer.WritePropertyName(nameof(NextCronExpressionOccurrence.ErrorMessage));
                        writer.WriteString(e.Message);
                        writer.WriteEndObject();
                        writer.Flush();
                    }

                return(Task.CompletedTask);
            }

            var nextOccurrence = crontabSchedule.GetNextOccurrence(SystemTime.UtcNow.ToLocalTime());

            using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName(nameof(NextCronExpressionOccurrence.IsValid));
                    writer.WriteBool(true);
                    writer.WriteComma();
                    writer.WritePropertyName(nameof(NextCronExpressionOccurrence.Utc));
                    writer.WriteDateTime(nextOccurrence.ToUniversalTime(), true);
                    writer.WriteComma();
                    writer.WritePropertyName(nameof(NextCronExpressionOccurrence.ServerTime));
                    writer.WriteDateTime(nextOccurrence, false);
                    writer.WriteEndObject();
                    writer.Flush();
                }

            return(Task.CompletedTask);
        }
Exemplo n.º 35
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 = SchedulerResolution.Current.CalculateNowInstant(nowInstant, timeZone, _schedule.GetNextOccurrence);
            NextInstant = TimeZoneInfo.ConvertTimeToUtc(
                _schedule.GetNextOccurrence(TimeZoneInfo.ConvertTimeFromUtc(NowInstant, _timeZone)),
                _timeZone);
        }
Exemplo n.º 36
0
 public static Schedule BuildSchedule(string cronExpression, TriggeredJobSchedulerLogger logger)
 {
     try
     {
         var crontabSchedule = CrontabSchedule.Parse(cronExpression, new CrontabSchedule.ParseOptions()
         {
             IncludingSeconds = true
         });
         return(crontabSchedule != null ? new Schedule(crontabSchedule, logger) : null);
     }
     catch (Exception ex)
     {
         logger.LogError("Failed to parse schedule \"{0}\". Error: {1}".FormatCurrentCulture(cronExpression, ex.Message));
         return(null);
     }
 }
        public SchedulerHostedService(IEnumerable <IScheduledTask> scheduledTasks, IServiceScopeFactory serviceScopeFactory)
        {
            var referenceTime = DateTime.UtcNow;

            foreach (var scheduledTask in scheduledTasks)
            {
                _scheduledTasks.Add(new SchedulerTaskWrapper
                {
                    Schedule    = CrontabSchedule.Parse(scheduledTask.Schedule),
                    Task        = scheduledTask,
                    NextRunTime = referenceTime
                });
            }

            _serviceScopeFactory = serviceScopeFactory ?? throw new ArgumentNullException(nameof(serviceScopeFactory));
        }
Exemplo n.º 38
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);
            NextInstant = TimeZoneInfo.ConvertTime(
                _schedule.GetNextOccurrence(TimeZoneInfo.ConvertTime(NowInstant, TimeZoneInfo.Utc, _timeZone)),
                _timeZone,
                TimeZoneInfo.Utc);
        }
Exemplo n.º 39
0
 public CronJob(CrontabSchedule schedule, string cronString, string command, string[] args)
 {
     Schedule = schedule;
     CronString = cronString;
     Command = command;
     Args = args;
 }
 /// <summary>
 /// Constructs a new instance based on the specified crontab schedule
 /// </summary>
 /// <param name="schedule">The crontab schedule to use</param>
 public CronSchedule(CrontabSchedule schedule)
 {
     _cronSchedule = schedule;
 }
Exemplo n.º 41
0
 public IScheduleInstant GetInstant(CrontabSchedule schedule)
 {
     return new ScheduleInstant(DateTime.UtcNow, schedule);
 }
Exemplo n.º 42
0
 public ScheduleInstantFactoryFacts()
 {
     _crontabSchedule = CrontabSchedule.Parse("* * * * *");
     _timeZone = TimeZoneInfo.Utc;
 }
Exemplo n.º 43
0
 public DateTime GetNextOccurrence(CrontabSchedule schedule)
 {
     return schedule.GetNextOccurrence(CurrentDateTime);
 }
Exemplo n.º 44
0
 public ScheduleInstantFacts()
 {
     _now = new DateTime(2012, 12, 12, 12, 12, 0, DateTimeKind.Utc);
     _schedule = CrontabSchedule.Parse("* * * * *");
     _timeZone = TimeZoneInfo.Utc;
 }
Exemplo n.º 45
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 = string.Format("{{0,-{0}:ddd}} {{0:dd}}, {{0,-{1}:MMM}} {{0:yyyy {2}}}", dayWidth, monthWidth, 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 = string.Format("Last count = {0}, Total = {1}",
                count.ToString("N0"), _totalOccurrenceCount.ToString("N0"));

            _resultBox.Text = sb.ToString();
            _resultBox.Select(0, 0);
            _resultBox.ScrollToCaret();
        }
Exemplo n.º 46
0
 public ScheduleInstantFacts()
 {
     _localTime = new DateTime(2012, 12, 12, 12, 12, 0, DateTimeKind.Utc);
     _schedule = CrontabSchedule.Parse("* * * * *");
 }
Exemplo n.º 47
0
 private Schedule(CrontabSchedule crontabSchedule, TriggeredJobSchedulerLogger logger)
 {
     _crontabSchedule = crontabSchedule;
     _logger = logger;
 }
Exemplo n.º 48
0
        public void GetNextInstants_DoesntThrow_NearDaylightSavings()
        {
            // Arrange
            _timeZone = GetNewYorkTimeZone();
            _now = TimeZoneInfo.ConvertTime(new DateTime(2016, 3, 13, 3, 0, 0), _timeZone, TimeZoneInfo.Utc);
            _schedule = CrontabSchedule.Parse("0 * * * *");

            var instant = CreateInstant();

            // Act
            var last = TimeZoneInfo.ConvertTime(new DateTime(2016, 3, 13, 1, 0, 0), _timeZone, TimeZoneInfo.Utc);
            var value = instant.GetNextInstants(last).ToList();

            // Assert
            Assert.Equal(1, value.Count);
            Assert.Equal(last.AddHours(1), value[0]);
        }