| | | 1 | | using Elsa.Common.RecurringTasks; |
| | | 2 | | using Microsoft.Extensions.DependencyInjection; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Common.Multitenancy.EventHandlers; |
| | | 6 | | |
| | 1 | 7 | | public class StartRecurringTasks(RecurringTaskScheduleManager scheduleManager, ILogger<StartRecurringTasks> logger) : IT |
| | | 8 | | { |
| | 1 | 9 | | private readonly ICollection<ScheduledTimer> _scheduledTimers = new List<ScheduledTimer>(); |
| | | 10 | | private CancellationTokenSource _cancellationTokenSource = null!; |
| | | 11 | | |
| | | 12 | | public async Task TenantActivatedAsync(TenantActivatedEventArgs args) |
| | | 13 | | { |
| | 1 | 14 | | var cancellationToken = args.CancellationToken; |
| | 1 | 15 | | _cancellationTokenSource = new CancellationTokenSource(); |
| | 1 | 16 | | var tenantScope = args.TenantScope; |
| | 1 | 17 | | var tasks = tenantScope.ServiceProvider.GetServices<IRecurringTask>().ToList(); |
| | 1 | 18 | | var taskExecutor = tenantScope.ServiceProvider.GetRequiredService<ITaskExecutor>(); |
| | | 19 | | |
| | 8 | 20 | | foreach (var task in tasks) |
| | | 21 | | { |
| | 3 | 22 | | var schedule = scheduleManager.GetScheduleFor(task.GetType()); |
| | 3 | 23 | | var timer = schedule.CreateTimer(async () => |
| | 3 | 24 | | { |
| | 3 | 25 | | try |
| | 3 | 26 | | { |
| | 2 | 27 | | await taskExecutor.ExecuteTaskAsync(task, _cancellationTokenSource.Token); |
| | 2 | 28 | | } |
| | 0 | 29 | | catch (OperationCanceledException e) |
| | 3 | 30 | | { |
| | 0 | 31 | | logger.LogInformation(e, "Task {TaskType} was cancelled", task.GetType().Name); |
| | 0 | 32 | | } |
| | 3 | 33 | | |
| | 5 | 34 | | }); |
| | 3 | 35 | | _scheduledTimers.Add(timer); |
| | 3 | 36 | | await task.StartAsync(cancellationToken); |
| | | 37 | | } |
| | 1 | 38 | | } |
| | | 39 | | |
| | | 40 | | public async Task TenantDeactivatedAsync(TenantDeactivatedEventArgs args) |
| | | 41 | | { |
| | 1 | 42 | | var tenantScope = args.TenantScope; |
| | 1 | 43 | | _cancellationTokenSource.Cancel(); |
| | 11 | 44 | | foreach (var timer in _scheduledTimers) await timer.DisposeAsync(); |
| | 1 | 45 | | _scheduledTimers.Clear(); |
| | 1 | 46 | | var tasks = tenantScope.ServiceProvider.GetServices<IRecurringTask>(); |
| | 11 | 47 | | foreach (var task in tasks) await task.StopAsync(args.CancellationToken); |
| | 1 | 48 | | } |
| | | 49 | | } |