Esempio n. 1
0
        public async Task RunAsync(CancellationToken cancellationToken)
        {
            _externalCancellationToken = cancellationToken;
            _externalCancellationToken.Register(() => _localCancellationTokenSource.Cancel());
            List <Guid> lowestIds = new List <Guid>();

            while (!cancellationToken.IsCancellationRequested)
            {
                var lowestNextTimeToRun = GetScheduledTasksToRunAndHowLongToWait(lowestIds);

                var timeToWait = lowestNextTimeToRun.Subtract(_cronDateTimeService.GetNow());

                var continueExecution = await Task.Delay((int)Math.Min(int.MaxValue, timeToWait.TotalMilliseconds), _localCancellationTokenSource.Token).ContinueWith(task =>
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    return(true);
                });

                if (!continueExecution)
                {
                    return;
                }

                var startTime = _cronDateTimeService.GetNow();
                foreach (var scheduledTask in _scheduledTasks.Where(m => lowestIds.Contains(m.Id)))
                {
                    if (_localCancellationTokenSource.IsCancellationRequested)
                    {
                        break;
                    }

                    try
                    {
                        if (scheduledTask.Action is object)
                        {
                            scheduledTask.Action.Invoke(_localCancellationTokenSource.Token);
                        }

                        if (scheduledTask.ActionTask is object)
                        {
                            await scheduledTask.ActionTask.Invoke(_localCancellationTokenSource.Token);
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, "Failed to execute action");
                    }
                }
                if (_cronDateTimeService.GetNow() - startTime > MINUTE)
                {
                    _logger.LogWarning("Execution took more than one minute");
                }
            }
        }
Esempio n. 2
0
        public DateTime?GetNextTimeToRun()
        {
            var now = _cronDateTimeService.GetNow();

            return(PrivateGetNextTimeToRun(now));
        }