public async Task RegisterJobAsync(IWhenDoJob job) { try { if (job.Schedule != null) { job.SetNextRun(DateTimeOffset.Now); //TODO: should be provider by datetimeprovider? } await jobRepository.SaveAsync(job); } catch (Exception ex) { logger.LogError(ex, $"Could not register job {job.Id}"); throw; } }
public void ExecuteJob(IWhenDoJob job, IWhenDoMessage context) { if (job.Commands.Count() == 0) { logger.LogWarning("Will not execute job {id} as it does not contain any commands", job.Id); return; } if (job.Type == JobType.Scheduled) { job.SetNextRun(dtp.Now); } job.LastRun = dtp.Now; jobRepository.SaveAsync(job); foreach (var command in job.Commands) { try { switch (command.ExecutionStrategy.Mode) { //case ExecutionMode.Default: // var commandExecutor = serviceProvider.GetRequiredService<IWhenDoCommandExecutor>(); // await commandExecutor.ExecuteAsync(context, command.Type, command.MethodName, command.Parameters); // break; case ExecutionMode.Default: case ExecutionMode.Reliable: { hangfireClient.Enqueue <IWhenDoCommandExecutor>(x => x.ExecuteAsync(context, job.Id, command.Id)); logger.LogInformation($"Set command {command.Type} for immediate execution"); } break; case ExecutionMode.Delayed: { var providers = GetExpressionProviderInstancesForDelegate(command.ExecutionStrategy.Time, null).ToArray(); var time = (TimeSpan)command.ExecutionStrategy.Time.DynamicInvoke(providers); hangfireClient.Schedule <IWhenDoCommandExecutor>(x => x.ExecuteAsync(context, job.Id, command.Id), time); logger.LogInformation($"Delayed command {command.Type} with {time.ToString()}"); } break; case ExecutionMode.Scheduled: { var providers = GetExpressionProviderInstancesForDelegate(command.ExecutionStrategy.Time, null).ToArray(); var today = DateTimeOffset.Now.Date; var time = (TimeSpan)command.ExecutionStrategy.Time.DynamicInvoke(providers); var executionTime = (today + time > DateTime.Now) ? today + time : today.AddDays(1) + time; hangfireClient.Schedule <IWhenDoCommandExecutor>(x => x.ExecuteAsync(context, job.Id, command.Id), executionTime); logger.LogInformation($"Scheduled command {command.Type} at {executionTime.ToString()}"); } break; } } catch (Exception ex) { logger.LogError(ex, $"Error when executing command {command.Id}: {ex.Message}"); } } }