# Workers

> Run long-running background processes.

URL: https://www.trakhound.com/docs/trakhound-framework/workers

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.

Diagram: When a Worker starts, its status is Starting and OnStartAsync runs, starting your loop and returning. The status becomes Started while the loop runs every interval. When it is stopped, the status is Stopping and OnStopAsync cancels the loop and waits for it, then the status is Stopped. An unhandled error sets the status to Error.

## 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](https://www.trakhound.com/docs/trakhound-framework/debugging)).

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

| Method | Called 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

| Property | Description |
| --- | --- |
| `Client` | Client used to call APIs, run Functions, and read and write [Services](https://www.trakhound.com/docs/trakhound-framework/services). |
| `Volume`, `Variables` | The Worker's [Volume and Variables](https://www.trakhound.com/docs/trakhound-framework/volumes-and-variables). |
| `Configuration` | The Worker's configuration. Read parameters with `Configuration.GetParameter(name)`. |
| `GetConfigurationVariable(name)` | Reads a [Configuration Variable](https://www.trakhound.com/docs/trakhound-framework/configuration#variables) shared by every configuration in the profile. |
| `Id`, `InstanceId`, `Package` | Information 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](https://www.trakhound.com/docs/trakhound-framework/zones) to limit what it can reach.
