w4c-workflows-api/Services/Triggers/TriggerDue.cs

37 lines
1.2 KiB
C#
Raw Normal View History

using w4c_workflows.Models;
namespace w4c_workflows.Services.Triggers;
/// <summary>
/// Pure due-check for scheduled triggers. Extracted from the scheduler so the
/// cron/interval timing rules are unit-testable without Redis/Postgres.
/// </summary>
public static class TriggerDue
{
/// <summary>
/// Whether a cron/interval trigger should fire now. A workflow with no
/// recorded last fire fires once on first discovery (the scheduler's initial
/// pass), then again when its schedule next elapses.
/// </summary>
public static bool IsDue(TriggerSpec spec, DateTimeOffset? lastFire, DateTimeOffset now)
{
if (lastFire == null)
return true;
if (spec.Type == TriggerType.Interval)
{
var interval = spec.Interval ?? TimeSpan.Zero;
return interval > TimeSpan.Zero && lastFire.Value + interval <= now;
}
if (spec.Type == TriggerType.Cron
&& CronExpression.TryParse(spec.Cron, out var cron, out _))
{
var next = cron!.GetNextOccurrence(lastFire.Value);
return next.HasValue && next.Value <= now;
}
return false;
}
}