private async Task ExecuteJobAsync(JobRegistration registration, IJob job, CancellationToken cancellationToken, string[] args = null) { if (registration?.Key.IsNullOrEmpty() == false && job != null) { try { async Task Execute() { // TODO: publish domain event (job started) this.logger.LogJournal(LogEventPropertyKeys.TrackStartJob, $"{{LogKey:l}} job started (key={{JobKey}}, id={registration.Identifier}, type={job.GetType().PrettyName()}, isReentrant={registration.IsReentrant}, timeout={registration.Timeout.ToString("c")})", args: new[] { LogEventKeys.JobScheduling, registration.Key }); await job.ExecuteAsync(cancellationToken, args).AnyContext(); await Run.DelayedAsync(new TimeSpan(0, 0, 1), () => { this.logger.LogJournal(LogEventPropertyKeys.TrackFinishJob, $"{{LogKey:l}} job finished (key={{JobKey}}, id={registration.Identifier}, type={job.GetType().PrettyName()})", args: new[] { LogEventKeys.JobScheduling, registration.Key }); return(Task.CompletedTask); }); // TODO: publish domain event (job finished) } if (!registration.IsReentrant) { if (this.mutex.TryAcquireLock(registration.Key)) { try { await Execute(); } finally { this.mutex.ReleaseLock(registration.Key); } } else { this.logger.LogWarning($"{{LogKey:l}} already executing (key={{JobKey}}, type={job.GetType().PrettyName()})", LogEventKeys.JobScheduling, registration.Key); } } else { await Execute(); } } catch (OperationCanceledException ex) { // TODO: publish domain event (job failed) this.logger.LogWarning(ex, $"{{LogKey:l}} canceled (key={{JobKey}}), type={job.GetType().PrettyName()})", LogEventKeys.JobScheduling, registration.Key); //this.errorHandler?.Invoke(ex); } catch (Exception ex) { // TODO: publish domain event (job failed) this.logger.LogError(ex.InnerException ?? ex, $"{{LogKey:l}} failed (key={{JobKey}}), type={job.GetType().PrettyName()})", LogEventKeys.JobScheduling, registration.Key); this.errorHandler?.Invoke(ex.InnerException ?? ex); } } }
public IJobScheduler UnRegister(JobRegistration registration) { if (registration != null) { this.Options.Registrations.Remove(registration); } return(this); }
public IJobScheduler Register(JobRegistration registration, IJob job) { EnsureArg.IsNotNull(registration, nameof(registration)); EnsureArg.IsNotNullOrEmpty(registration.Cron, nameof(registration.Cron)); EnsureArg.IsNotNull(job, nameof(job)); registration.Key = registration.Key ?? HashAlgorithm.ComputeHash(job); this.logger.LogInformation($"{{LogKey:l}} registration (key={{JobKey}}, id={registration.Identifier}, cron={registration.Cron}, isReentrant={registration.IsReentrant}, timeout={registration.Timeout.ToString("c")}, enabled={registration.Enabled})", LogKeys.JobScheduling, registration.Key); var item = this.Options.Registrations.FirstOrDefault(r => r.Key.Key.SafeEquals(registration.Key)); if (item.Key != null) { this.Options.Registrations.Remove(item.Key); } this.Options.Registrations.Add(registration, job); return(this); }