Skip to content

Commit fddc917

Browse files
committed
Improve exception handling in ScheduledTimer and TenantTaskManager
- Add try-catch block in `ScheduledTimer` to handle exceptions without crashing application during shutdown. - Log error messages in `TenantTaskManager` when exceptions occur
1 parent 6cd3a53 commit fddc917

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

src/modules/Elsa.Common/Multitenancy/EventHandlers/TenantTaskManager.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,10 @@ private async Task StartRecurringTasksAsync(ITenantScope tenantScope, ITaskExecu
118118
{
119119
logger.LogInformation(e, "Recurring task {TaskType} was cancelled", task.GetType().Name);
120120
}
121+
catch (Exception e)
122+
{
123+
logger.LogError(e, "An error occurred while executing recurring task {TaskType}", task.GetType().Name);
124+
}
121125
});
122126

123127
_scheduledTimers.Add(timer);

src/modules/Elsa.Common/RecurringTasks/ScheduledTimer.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,24 @@ public ScheduledTimer(Func<Task> action, Func<TimeSpan> interval)
1515

1616
private async void Callback(object? state)
1717
{
18-
await _action();
19-
_timer.Change(_interval(), Timeout.InfiniteTimeSpan);
18+
try
19+
{
20+
try
21+
{
22+
await _action();
23+
}
24+
catch (Exception)
25+
{
26+
// The action failed, but we still want to reschedule the timer.
27+
}
28+
29+
_timer.Change(_interval(), Timeout.InfiniteTimeSpan);
30+
}
31+
catch (Exception)
32+
{
33+
// Ignore exceptions to prevent process crash (async void).
34+
// This is especially important during application shutdown where the timer or dependencies might be disposed.
35+
}
2036
}
2137

2238
public void Dispose()

0 commit comments

Comments
 (0)