Ejemplo n.º 1
0
        private async Task RunAsync(ProcessableCronJob job, TaskContext context)
        {
            var cronSchedule = job.Schedule;
            var nowInstant   = _instantFactory(cronSchedule, timeZone);

            var lastInstant = GetLastInstant(job, nowInstant);

            if (nowInstant.GetNextInstants(lastInstant).Any())
            {
                using (var scopedContext = _serviceProvider.CreateScope())
                {
                    var provider = scopedContext.ServiceProvider;
                    var cronJob  = (IJob)provider.GetService(job.Type);
                    job.CreatedAt = nowInstant.NowInstant;
                    try
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        await cronJob.InvokeAsync(context);

                        sw.Stop();
                        job.LastRun = nowInstant.NowInstant;
                        _logger.LogDebug($"{job.ToString()} is executed. Utc: {nowInstant.NowInstant}, TotalSeconds: {sw.Elapsed.TotalSeconds}");
                    }
                    catch (Exception ex)
                    {
                        _jobStorage.Set(cronJob.Id, cronJob);
                        _logger.LogError(ex, $"{nameof(CronJobScheduler)} exception");
                    }

                    job.Next = nowInstant.NextInstant.HasValue ? (DateTime?)nowInstant.NextInstant.Value : null;
                }
            }
        }
Ejemplo n.º 2
0
        private DateTime GetLastInstant(ProcessableCronJob job, IScheduleInstant instant)
        {
            DateTime lastInstant;

            if (job.LastRun != default(DateTime))
            {
                lastInstant = job.LastRun;
            }
            else if (job.CreatedAt != default(DateTime))
            {
                lastInstant = job.CreatedAt;
            }
            else if (job.Next.HasValue)
            {
                lastInstant = job.Next.Value;
                lastInstant = lastInstant.AddSeconds(-1);
            }
            else
            {
                lastInstant = instant.NowInstant.AddSeconds(-1);
            }

            return(lastInstant);
        }