// Calculate the next scheduled run for a task // Based off of a cron expression for the schedule public static DateTime CalculateNextRun(DateTime currentSched, string scheduleCron) { CrontabSchedule sched = CrontabSchedule.Parse(scheduleCron); DateTime today = DateTime.Today; DateTime end = new DateTime(2100, 12, 31); DateTime nextSched = sched.GetNextOccurrence(currentSched, end); bool isLastOfMonth = scheduleCron.Substring(0, scheduleCron.Length).Contains("28-31"); if (isLastOfMonth) { while (nextSched.Day != DateTime.DaysInMonth(nextSched.Year, nextSched.Month)) { nextSched = nextSched.AddDays(1); } } while (nextSched <= today) { nextSched = sched.GetNextOccurrence(nextSched, end); if (nextSched.Month == today.Month && isLastOfMonth) { while (nextSched.Day != DateTime.DaysInMonth(nextSched.Year, nextSched.Month)) { nextSched = nextSched.AddDays(1); } } } return(nextSched); }
public BedrockServiceWrapper(bool throwOnStart, bool throwOnStop, bool throwUnhandled) { try { _settings = AppSettings.Instance; bedrockServers = new List <BedrockServerWrapper>(); _settings.ServerConfig.ForEach(t => bedrockServers.Add(new BedrockServerWrapper(t, _settings.BackupConfig))); if (_settings.BackupConfig.BackupOn && _settings.BackupConfig.BackupIntervalMinutes > 0) { backupTimer = new System.Timers.Timer(_settings.BackupConfig.BackupIntervalMinutes * 60000); backupTimer.Elapsed += BackupTimer_Elapsed; backupTimer.Start(); } shed = CrontabSchedule.TryParse(_settings.BackupConfig.BackupIntervalCron); if (_settings.BackupConfig.BackupOn && shed != null) { var nextRun = shed.GetNextOccurrence(DateTime.Now); cronTimer = new System.Timers.Timer((shed.GetNextOccurrence(DateTime.Now) - DateTime.Now).TotalMilliseconds); cronTimer.Elapsed += CronTimer_Elapsed; cronTimer.Start(); } } catch (Exception e) { _log.Fatal("Error Instantiating BedrockServiceWrapper", e); } }
public static bool UpdateTaskFromSchedule(Event @event) { CrontabSchedule schedule = CrontabSchedule.TryParse( @event.EventFrequency.GetCronValue(), new CrontabSchedule.ParseOptions { IncludingSeconds = true }); if (schedule != null) { if (crontabSchedule.ContainsKey(@event.Id)) { crontabSchedule[@event.Id] = schedule; crontabNextRun[@event.Id] = schedule.GetNextOccurrence(DateTime.UtcNow); } else { crontabSchedule.Add(@event.Id, schedule); crontabNextRun.Add(@event.Id, schedule.GetNextOccurrence(DateTime.UtcNow)); } } else { crontabSchedule.Remove(@event.Id); crontabNextRun.Remove(@event.Id); } return(true); }
public void Run(TaskService <bool> task, CancellationToken cancellationToken) { CrontabSchedule _schedule = CrontabSchedule.Parse(task.Expression, new CrontabSchedule.ParseOptions { IncludingSeconds = true }); var _nextRun = _schedule.GetNextOccurrence(DateTime.Now); while (!cancellationToken.IsCancellationRequested) { var now = DateTime.Now; if (now > _nextRun) { Debug.WriteLine($"Debug start: ${task.Name}"); if (task.Fork) { Task.Factory.StartNew(() => { task.Func(); }); } else { task.Func(); } _nextRun = _schedule.GetNextOccurrence(DateTime.Now); } Thread.Sleep(1500); } }
private static TimeSpan CompareTwoCronOccurrences(CrontabSchedule schedule) { var from = schedule.GetNextOccurrence(DateTime.Now); // <-- throw this one away to normalize from = schedule.GetNextOccurrence(from); var to = schedule.GetNextOccurrence(from); var diff = to - from; return(diff); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { do { var now = DateTime.Now; var nextrun = _schedule.GetNextOccurrence(now); if (now > _nextRun) { Process(); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); } }while (!stoppingToken.IsCancellationRequested); }
public void Every_nth_and_mth_weekday(DayOfWeek n, DayOfWeek m, int expected) { string cron = CronTemplates.WeekDaily(onDays: new[] { n, m }); CrontabSchedule schedule = CrontabSchedule.Parse(cron); // These tests would be temporal if we used 'now', so must start from a known fixed date DateTime start = new DateTime(2016, 9, 4); DateTime from = schedule.GetNextOccurrence(start); // should always start on 9/5/2016 (Monday) DateTime to = schedule.GetNextOccurrence(from); TimeSpan diff = to - from; Assert.Equal(expected, diff.Days); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { do { var now = DateTime.Now; var nextrun = _schedule.GetNextOccurrence(now); if (now > _nextRun) { LeadsProcess(); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); } await Task.Delay(5000, stoppingToken); //5 seconds delay }while (!stoppingToken.IsCancellationRequested); }
protected override async Task ExecuteAsync(CancellationToken cancellationToken) { do { var now = DateTime.Now; var nextRun = _schedule.GetNextOccurrence(now); if (now > _nextRun) { await Process(); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); } await Task.Delay(5000, cancellationToken); }while (!cancellationToken.IsCancellationRequested); }
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); }
protected ScheduledProcessor(IServiceScopeFactory serviceScopeFactory) : base(serviceScopeFactory) { _schedule = CrontabSchedule.Parse(Schedule); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); Log.Information($"[Background-service] - {TaskName} | {_nextRun:dd-MM-yyyy HH:mm:ss}"); }
public override async Task <string> RunTask(OrchestrationContext context, string cronSchedule) { var numberOfTimes = 4; var runAfterEverySeconds = 10; for (var i = 1; i <= numberOfTimes; i++) { ServiceEventSource.Current.Message($"Schedule CronTask({i}) start"); DateTime currentTime = context.CurrentUtcDateTime; DateTime fireAt; if (string.IsNullOrWhiteSpace(cronSchedule)) { fireAt = currentTime.AddSeconds(runAfterEverySeconds); } else { CrontabSchedule schedule = CrontabSchedule.Parse(cronSchedule); fireAt = schedule.GetNextOccurrence(context.CurrentUtcDateTime); } string attempt = await context.CreateTimer(fireAt, i.ToString()); ServiceEventSource.Current.Message($"Schedule CronTask({i}) at {fireAt}"); Task <string> resultTask = context.ScheduleTask <string>(typeof(CronTask), attempt); await resultTask; } return("Done"); }
public ExchangeRateRefreshService(IConfiguration configuration, IExchangeRatesService exchangeRatesService) { _schedule = CrontabSchedule.Parse(configuration.GetValue <string>("ExchangeRateRefreshCronSchedule")); _nextExecution = _schedule.GetNextOccurrence(DateTime.Now); _exchangeRatesService = exchangeRatesService; }
private string Schedule => "*/10 * * * * *"; //Runs every 10 seconds public FineService() { _schedule = CrontabSchedule.Parse(Schedule, new CrontabSchedule.ParseOptions { IncludingSeconds = true }); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); }
protected CronScheduledService( IServiceScopeFactory serviceScopeFactory, string cronSchedule) : base(serviceScopeFactory) { _schedule = CrontabSchedule.Parse(cronSchedule); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); }
/// <summary> /// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts. /// </summary> /// <param name="args">Data passed by the start command.</param> protected override void OnStart(string[] args) { var taskClassType = typeof(T); _invokeMethodInfo = taskClassType.GetMethod(InvokeMethodName); if (_invokeMethodInfo == null) { throw new ServiceInitializationException(string.Format("Method {0} not found in class {1}", InvokeMethodName, taskClassType.Name)); } _isParameterlessMethod = !_invokeMethodInfo.GetParameters().Any(); if (!string.IsNullOrEmpty(Settings.CrontabExpression)) { _schedule = CrontabSchedule.TryParse(Settings.CrontabExpression); if (_schedule == null) { throw new ServiceInitializationException(string.Format("Crontab expression parsing failed, expression: '{0}'", Settings.CrontabExpression)); } _nextOccurrence = _schedule.GetNextOccurrence(TimeProvider.Current.Now); _timer = new Timer(OnCronTimerTick, null, 1000, 60000); } else { _timer = new Timer(OnStartWork, null, 1000, Settings.ProcessingInterval * 1000); } base.OnStart(args); }
public override async Task <string> RunTask(OrchestrationContext context, string cronSchedule) { int numberOfTimes = 4; bool waitForCompletion = false; int runAfterEverySeconds = 10; for (int i = 1; i <= numberOfTimes; i++) { DateTime currentTime = context.CurrentUtcDateTime; DateTime fireAt; if (string.IsNullOrWhiteSpace(cronSchedule)) { fireAt = currentTime.AddSeconds(runAfterEverySeconds); } else { CrontabSchedule schedule = CrontabSchedule.Parse(cronSchedule); fireAt = schedule.GetNextOccurrence(context.CurrentUtcDateTime); } var attempt = await context.CreateTimer <string>(fireAt, i.ToString()); Task <string> resultTask = context.ScheduleTask <string>(typeof(CronTask), attempt); if (waitForCompletion) { await resultTask; } } return("Done"); }
internal async Task <bool> StartIfScheduledAsync(DateTime now, CancellationToken cancellationToken = default(CancellationToken)) { var nextDate = _cronSchedule.GetNextOccurrence(now.AddMinutes(-1)); // not time yet if (nextDate > now) { return(false); } // check if already run if (LastRun != null && LastRun.Value == nextDate) { return(false); } return(await _lockProvider.TryUsingAsync(GetLockKey(nextDate), t => { LastRun = nextDate; // start running the job in a thread RunTask = Task.Factory.StartNew(() => { _runner.RunAsync(cancellationToken).GetAwaiter().GetResult(); }, cancellationToken); return Task.CompletedTask; }, TimeSpan.Zero, TimeSpan.Zero)); }
private async Task Run() { while (!_cancellationTokenSource.Token.IsCancellationRequested) { var now = DateTime.Now; if (now > _nextOccurrence) { if (_processTask == null) { _processTask = Process(_cancellationTokenSource.Token); } try { await _processTask; } finally { _processTask = null; } _nextOccurrence = _schedule.GetNextOccurrence(DateTime.Now); } await Task.Delay(TimeSpan.FromSeconds(5), _cancellationTokenSource.Token); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await Task.Yield(); _logger.LogInformation("ScheduledService started"); while (!stoppingToken.IsCancellationRequested) { try { var now = DateTime.Now; if (now > _nextRun) { await Process(); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); } } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception occurred, will retry processing at next interval"); } await Task.Delay(15000, stoppingToken); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { var now = DateTime.Now; var nextrun = _schedule.GetNextOccurrence(now); if (now > _nextRun) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); new Commit(_serviceSlack); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); } await Task.Delay(1000 * 60, stoppingToken); } }
protected CronService(string cron) { _schedule = Parse(cron, new ParseOptions { IncludingSeconds = true }); nextRun = _schedule.GetNextOccurrence(DateTime.Now); }
private void UpdateTimer_Elapsed(object sender, ElapsedEventArgs e) { try { if (updaterTimer != null) { updaterTimer.Stop(); updaterTimer = null; } Task<bool> task = Updater.CheckUpdates(); task.Wait(); if (InstanceProvider.GetHostInfo().GetGlobalValue("CheckUpdates") == "true" && updater != null && task.Result) { if (Updater.VersionChanged) { InstanceProvider.GetServiceLogger().AppendLine("Version change detected! Restarting server(s) to apply update..."); if (Stop(_hostControl)) { Start(_hostControl); } } updaterTimer = new System.Timers.Timer((updater.GetNextOccurrence(DateTime.Now) - DateTime.Now).TotalMilliseconds); updaterTimer.Elapsed += UpdateTimer_Elapsed; updaterTimer.Start(); } } catch (Exception ex) { _log.Error("Error in UpdateTimer_Elapsed", ex); } }
public SubscriptionRenewal(IConfiguration configuration) { _schedule = CrontabSchedule.Parse(Schedule, new CrontabSchedule.ParseOptions { IncludingSeconds = true }); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); /* _context = new DBContext(configuration.GetConnectionString("AIHoldingDB"));*/ }
public void NextOccurrence_ReturnsCorrectValue() { var instant = CreateInstant(); var value = instant.NextOccurrence; Assert.Equal(_schedule.GetNextOccurrence(_utcTime), value); }
public CronJobService(ICheckExpirationService check) { _check = check; _schedule = CrontabSchedule.Parse(Schedule); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); }
private string Schedule => "*/10 * * * * *"; //Runs every 10 seconds public LeadShcedulerService(IApplicationDbContextFactory applicationDbContextFactory) { ApplicationDbContextFactory = applicationDbContextFactory; _schedule = CrontabSchedule.Parse(Schedule, new CrontabSchedule.ParseOptions { IncludingSeconds = true }); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); }
public void Activate(CancellationToken token) { _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token); _schedule = CrontabSchedule.Parse(_folderConfiguration.Schedule); _nextOccurrence = _schedule.GetNextOccurrence(DateTime.Now); _runningTask = Task.Factory.StartNew(Run, TaskCreationOptions.LongRunning); }
public ScheduledService(IOptions <AppSettings> appSettings, ILogger <ScheduledService> logger, IHttpClientFactory clientFactory) { _schedule = CrontabSchedule.Parse(Schedule); _nextRun = _schedule.GetNextOccurrence(DateTime.Now); _appSettings = appSettings.Value; _logger = logger; _clientFactory = clientFactory; }
private string Schedule => "*/10 * * * * *"; //Runs every 10 seconds //* * * * * * //- - - - - - //| | | | | | //| | | | | +--- day of week(0 - 6) (Sunday=0) //| | | | +----- month(1 - 12) //| | | +------- day of month(1 - 31) //| | +--------- hour(0 - 23) //| +----------- min(0 - 59) //+------------- sec(0 - 59) public YilCronHostedService(ISensorTransactionCheckService sensorTransactionService) { this.sensorTransactionService = sensorTransactionService; _schedule = CrontabSchedule.Parse(Schedule, new CrontabSchedule.ParseOptions { IncludingSeconds = true }); _nextRun = _schedule.GetNextOccurrence(DefaultValue.Today); }
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); }
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); }
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); }
public DateTime GetNextOccurrence(CrontabSchedule schedule) { return schedule.GetNextOccurrence(CurrentDateTime); }