elsa-core/src/modules/Elsa.Scheduling/Activities/Timer.cs

58 lines
2.1 KiB
C#
Raw Normal View History

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;
2022-01-04 08:42:12 +00:00
namespace Elsa.Scheduling.Activities;
2022-01-04 08:42:12 +00:00
/// <summary>
2022-03-07 11:01:27 +00:00
/// Represents a timer to periodically trigger the workflow.
/// </summary>
2022-03-24 11:29:39 +00:00
[Activity( "Elsa", "Scheduling", "Trigger workflow execution at a specific interval.")]
2022-03-07 11:01:27 +00:00
public class Timer : EventGenerator
2022-01-04 08:42:12 +00:00
{
/// <inheritdoc />
2022-03-15 12:01:10 +00:00
[JsonConstructor]
public Timer([CallerFilePath] string? source = default, [CallerLineNumber] int? line = default) : base(source, line)
2022-03-15 12:01:10 +00:00
{
}
/// <inheritdoc />
public Timer(TimeSpan interval, [CallerFilePath] string? source = default, [CallerLineNumber] int? line = default) : this(new Input<TimeSpan>(interval), source, line)
2022-03-15 12:01:10 +00:00
{
}
/// <inheritdoc />
public Timer(Input<TimeSpan> interval, [CallerFilePath] string? source = default, [CallerLineNumber] int? line = default) : this(source, line)
2022-03-15 12:01:10 +00:00
{
Interval = interval;
}
/// <summary>
/// Th interval at which the timer should execute.
/// </summary>
2022-01-04 08:42:12 +00:00
[Input] public Input<TimeSpan> Interval { get; set; } = default!;
/// <inheritdoc />
2022-08-10 14:02:53 +00:00
protected override object GetTriggerPayload(TriggerIndexingContext context)
{
var interval = context.ExpressionExecutionContext.Get(Interval);
var clock = context.ExpressionExecutionContext.GetRequiredService<ISystemClock>();
var executeAt = clock.UtcNow.Add(interval);
return new TimerPayload(executeAt, interval);
}
2022-03-15 12:01:10 +00:00
/// <summary>
/// Creates a new <see cref="Timer"/> activity set to trigger at the specified interval.
/// </summary>
2022-03-15 12:01:10 +00:00
public static Timer FromTimeSpan(TimeSpan value) => new(value);
/// <summary>
/// Creates a new <see cref="Timer"/> activity set to trigger at the specified interval in seconds.
/// </summary>
2022-03-15 12:01:10 +00:00
public static Timer FromSeconds(double value) => FromTimeSpan(TimeSpan.FromSeconds(value));
2022-01-14 12:54:17 +00:00
}
internal record TimerPayload(DateTimeOffset StartAt, TimeSpan Interval);