< Summary

Information
Class: Elsa.Common.RecurringTasks.ScheduledTimer
Assembly: Elsa.Common
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Common/RecurringTasks/ScheduledTimer.cs
Line coverage
65%
Covered lines: 13
Uncovered lines: 7
Coverable lines: 20
Total lines: 54
Line coverage: 65%
Branch coverage
0%
Covered branches: 0
Total branches: 2
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
Callback()0%3250%
Dispose()100%210%
DisposeAsync()100%11100%

File(s)

/home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Common/RecurringTasks/ScheduledTimer.cs

#LineLine coverage
 1using Microsoft.Extensions.Logging;
 2
 3namespace Elsa.Common.RecurringTasks;
 4
 5public 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
 8412    public ScheduledTimer(Func<Task> action, Func<TimeSpan> interval, ILogger? logger = null)
 13    {
 8414        _action = action;
 8415        _interval = interval;
 8416        _logger = logger;
 8417        _timer = new Timer(Callback, null, interval(), Timeout.InfiniteTimeSpan);
 8418    }
 19
 20    private async void Callback(object? state)
 21    {
 22        try
 23        {
 213124            await _action();
 213125        }
 026        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.
 030            _logger?.LogError(e, "Unhandled exception in scheduled timer action");
 031        }
 32        finally
 33        {
 34            try
 35            {
 213136                _timer.Change(_interval(), Timeout.InfiniteTimeSpan);
 213137            }
 038            catch (ObjectDisposedException)
 39            {
 40                // Timer was disposed, ignore.
 041            }
 42        }
 213143    }
 44
 45    public void Dispose()
 46    {
 047        _timer.Dispose();
 048    }
 49
 50    public async ValueTask DisposeAsync()
 51    {
 3652        await _timer.DisposeAsync();
 3653    }
 54}