| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | |
| | | 3 | | namespace Elsa.Common.RecurringTasks; |
| | | 4 | | |
| | | 5 | | public class ScheduledTimer : IDisposable, IAsyncDisposable |
| | | 6 | | { |
| | | 7 | | private readonly Func<Task> _action; |
| | | 8 | | private readonly Func<TimeSpan> _interval; |
| | | 9 | | private readonly Timer _timer; |
| | | 10 | | private readonly ILogger? _logger; |
| | | 11 | | |
| | 84 | 12 | | public ScheduledTimer(Func<Task> action, Func<TimeSpan> interval, ILogger? logger = null) |
| | | 13 | | { |
| | 84 | 14 | | _action = action; |
| | 84 | 15 | | _interval = interval; |
| | 84 | 16 | | _logger = logger; |
| | 84 | 17 | | _timer = new Timer(Callback, null, interval(), Timeout.InfiniteTimeSpan); |
| | 84 | 18 | | } |
| | | 19 | | |
| | | 20 | | private async void Callback(object? state) |
| | | 21 | | { |
| | | 22 | | try |
| | | 23 | | { |
| | 2131 | 24 | | await _action(); |
| | 2131 | 25 | | } |
| | 0 | 26 | | catch (Exception e) |
| | | 27 | | { |
| | | 28 | | // Swallow exception to prevent async void from crashing the process. |
| | | 29 | | // Log unhandled exceptions here as a safeguard; calling code may have its own exception handling. |
| | 0 | 30 | | _logger?.LogError(e, "Unhandled exception in scheduled timer action"); |
| | 0 | 31 | | } |
| | | 32 | | finally |
| | | 33 | | { |
| | | 34 | | try |
| | | 35 | | { |
| | 2131 | 36 | | _timer.Change(_interval(), Timeout.InfiniteTimeSpan); |
| | 2131 | 37 | | } |
| | 0 | 38 | | catch (ObjectDisposedException) |
| | | 39 | | { |
| | | 40 | | // Timer was disposed, ignore. |
| | 0 | 41 | | } |
| | | 42 | | } |
| | 2131 | 43 | | } |
| | | 44 | | |
| | | 45 | | public void Dispose() |
| | | 46 | | { |
| | 0 | 47 | | _timer.Dispose(); |
| | 0 | 48 | | } |
| | | 49 | | |
| | | 50 | | public async ValueTask DisposeAsync() |
| | | 51 | | { |
| | 36 | 52 | | await _timer.DisposeAsync(); |
| | 36 | 53 | | } |
| | | 54 | | } |