using System.Runtime.CompilerServices; using System.Text.Json.Serialization; using Elsa.Common.Contracts; using Elsa.Extensions; using Elsa.Workflows.Core.Attributes; using Elsa.Workflows.Core.Models; namespace Elsa.Scheduling.Activities; /// /// Represents a timer to periodically trigger the workflow. /// [Activity( "Elsa", "Scheduling", "Trigger workflow execution at a specific interval.")] public class Timer : EventGenerator { /// [JsonConstructor] public Timer([CallerFilePath] string? source = default, [CallerLineNumber] int? line = default) : base(source, line) { } /// public Timer(TimeSpan interval, [CallerFilePath] string? source = default, [CallerLineNumber] int? line = default) : this(new Input(interval), source, line) { } /// public Timer(Input interval, [CallerFilePath] string? source = default, [CallerLineNumber] int? line = default) : this(source, line) { Interval = interval; } /// /// Th interval at which the timer should execute. /// [Input] public Input Interval { get; set; } = default!; /// protected override object GetTriggerPayload(TriggerIndexingContext context) { var interval = context.ExpressionExecutionContext.Get(Interval); var clock = context.ExpressionExecutionContext.GetRequiredService(); var executeAt = clock.UtcNow.Add(interval); return new TimerPayload(executeAt, interval); } /// /// Creates a new activity set to trigger at the specified interval. /// public static Timer FromTimeSpan(TimeSpan value) => new(value); /// /// Creates a new activity set to trigger at the specified interval in seconds. /// public static Timer FromSeconds(double value) => FromTimeSpan(TimeSpan.FromSeconds(value)); } internal record TimerPayload(DateTimeOffset StartAt, TimeSpan Interval);