Do not use Task.Delay or Thread.Sleep. Use the ExecuteScheduledTask method to run periodic logic without blocking the message loop.
using Proxus.SDK.BaseFunctions;
using Proxus.Common.Messages;
using Proxus.Common;
using System;
using System.Threading;
namespace MyProject.Functions
{
public class ShiftReset : FunctionBase
{
private CancellationTokenSource _scheduler;
public ShiftReset(object sys, object log, object config) : base(sys, log, config) { }
protected override void OnStarted()
{
// 1. Schedule a task every hour
// align: true -> Ensures it runs at xx:00:00 (Top of the hour)
_scheduler = ExecuteScheduledTask(
TimeSpan.FromHours(1),
OnShiftChange,
align: true
);
base.OnStarted();
}
private async void OnShiftChange()
{
LogInformation($"Executing Shift Sequence: {DateTime.Now}");
// 2. Create a Control Packet
var syncPacket = new TransportDataBuilder()
.WithTopic("Global/Sync")
.WithPayload("Command", "ResetCounters")
.WithAttribute("Source", this.GatewayId)
.Build();
// 3. Broadcast to ALL other Gateways in the cluster
await PublishToEdgeGateways(syncPacket);
}
protected override void OnStopping()
{
_scheduler?.Cancel();
base.OnStopping();
}
}
}