Workers

Run long-running background processes.
Framework Docs Menu

A Worker is a long-running background process. Workers are typically used to process, import, or export data that requires maintaining a constant connection or subscription, such as reading from a machine or a message broker.

StartingOnStartAsync() starts your loop, then returns
StartedThe loop runs every interval (ex. 5 seconds)
Stop
StoppingOnStopAsync() cancels the loop and waits for it
StoppedCan be started again
Started with the Instance, and from Explorer > Workers with Start and Stop
Error: an unhandled exception. Catch errors inside the loop so one failure doesn't stop the Worker
Don't block in OnStartAsync: start the loop and return, so the Instance can finish starting.

Create a Worker

dotnet new trakhound.worker
using TrakHound;
using TrakHound.Workers;

public class Worker : TrakHoundWorker
{
    private CancellationTokenSource _stop;
    private Task _loop;

    public Worker(ITrakHoundWorkerConfiguration configuration) : base(configuration) { }

    protected override Task OnStartAsync()
    {
        // The "interval" parameter (milliseconds) set in the Worker's configuration
        var interval = Configuration.GetParameter<int>("interval");
        if (interval <= 0) interval = 5000;

        _stop = new CancellationTokenSource();
        _loop = Run(TimeSpan.FromMilliseconds(interval), _stop.Token);
        return Task.CompletedTask;
    }

    protected override async Task OnStopAsync()
    {
        _stop.Cancel();
        await _loop;
        _stop.Dispose();
    }

    private async Task Run(TimeSpan interval, CancellationToken cancellationToken)
    {
        using var timer = new PeriodicTimer(interval);
        try
        {
            while (await timer.WaitForNextTickAsync(cancellationToken))
            {
                try
                {
                    await Client.Services.Messages.Publish("example/heartbeat", DateTime.UtcNow.ToString("o"));
                }
                catch (Exception ex)
                {
                    // Log and continue, so one failure doesn't stop the Worker
                    Log(TrakHoundLogLevel.Error, ex.Message);
                }
            }
        }
        catch (OperationCanceledException) { }
    }
}

Start your own loop or timer in OnStart and end it in OnStop, as above. Don't block in OnStart: return once the loop is running. The template's loop runs every interval milliseconds (a configuration parameter, default 5000), and its Program.cs starts the Worker locally with the parameters in trakhound.debug.json and stops it on Ctrl+C (see Debugging & Testing).

The Instance creates the Worker with its configuration, then sets Client, Volume, and Variables. The older (configuration, client, volume) constructor still loads, but is only kept for existing Packages.

Lifecycle

MethodCalled when
OnStart() / OnStartAsync()The Worker is started.
OnStop() / OnStopAsync()The Worker is stopped or disposed. Runs once per start.
OnDispose()The Worker is disposed. Release any remaining resources here.

Report progress with UpdateStatus(status, message). Volume.CreateListener(path) raises an event when files in the Worker's Volume change, for example to reload settings.

Workers can be started and stopped from the Explorer in the admin UI, which also shows each Worker's status, CPU usage, log, and Volume. Diagnostics > Metrics > Workers shows uptime, availability, restarts, and errors for each Worker.

Worker Properties

PropertyDescription
ClientClient used to call APIs, run Functions, and read and write Services.
Volume, VariablesThe Worker's Volume and Variables.
ConfigurationThe Worker's configuration. Read parameters with Configuration.GetParameter(name).
GetConfigurationVariable(name)Reads a Configuration Variable shared by every configuration in the profile.
Id, InstanceId, PackageInformation about the Worker and Instance.
Calls a Worker makes through its Client have no signed-in caller, so they are trusted by security profiles. Add the Worker to a Zone to limit what it can reach.