| | | 1 | | using System.ComponentModel; |
| | | 2 | | using Elsa.Common; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Workflows.CommitStates.Strategies; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Implements a periodic workflow commit strategy based on a specified time interval. |
| | | 8 | | /// This strategy determines if a workflow should commit by comparing the elapsed time |
| | | 9 | | /// since the last commit with the configured interval. |
| | | 10 | | /// </summary> |
| | | 11 | | [DisplayName("Commit Periodically")] |
| | | 12 | | [Description("Determines whether a workflow state should be committed based on a specified time interval.")] |
| | 1 | 13 | | public class PeriodicWorkflowStrategy(TimeSpan interval) : IWorkflowCommitStrategy |
| | | 14 | | { |
| | 0 | 15 | | private static readonly object LastCommitPropertyKey = new(); |
| | 1 | 16 | | public TimeSpan Interval { get; } = interval; |
| | | 17 | | |
| | | 18 | | public CommitAction ShouldCommit(WorkflowCommitStateStrategyContext context) |
| | | 19 | | { |
| | 0 | 20 | | var lastCommit = context.WorkflowExecutionContext.TransientProperties.TryGetValue(LastCommitPropertyKey, out var |
| | 0 | 21 | | var now = context.WorkflowExecutionContext.GetRequiredService<ISystemClock>().UtcNow; |
| | 0 | 22 | | var shouldCommit = lastCommit == null || (now - lastCommit.Value).TotalMilliseconds > Interval.TotalMilliseconds |
| | | 23 | | |
| | 0 | 24 | | if (shouldCommit) |
| | 0 | 25 | | context.WorkflowExecutionContext.TransientProperties[LastCommitPropertyKey] = now; |
| | | 26 | | |
| | 0 | 27 | | return shouldCommit ? CommitAction.Commit : CommitAction.Default; |
| | | 28 | | } |
| | | 29 | | } |