Mib Worker
The MibWorker
class is an abstract class that extends BackgroundService
. Its primary purpose is to provide a framework for executing asynchronous tasks with periodic heartbeats. The MibWorker
class is designed to:
- Manage Worker Identity: Each instance of the worker is assigned an unique ID.
- Manage Heartbeats: Controls the interval between heartbeats and the calling of the work that should be performed.
- Manage Logging: Provides a final layer for capturing unhandled exceptions and logging.
A concrete worker that implements MibWorker has access to the following properties:
- Id: A unique identifier for the worker.
- Name: The name of the worker.
- HeartbeatId: A unique identifier for each heartbeat cycle, which can be used as request id when making api calls.
- Logger: An instance of
IMibLog
, setup to prefix the messages with the HeartbeatId. Each worker logs in its own file.
How to create a Mib Worker
The following steps will guide you through the creation of a MibWorker and using the extension methods to run them as IHostedService in your .NET application.
1. Add reference to the NuGet package
MediaiBox.Workers
2. Implement MibWorker
public class ConcreteWorker : MibWorker
{
//Implement this abstract method, which is called between hearbeats to perform the actual work.
protected override async Task ExecuteWorkAsync(CancellationToken stoppingToken)
{
// It's recommended to handle all exceptions within this method.
try
{
// Perform the async work
}
catch(Exception ex)
{
// Log exception
}
}
}
3. Customize using MibWorkerConfig
The behavior of the implemented MibWorker is controlled by MibWorkerConfig. Although default values are supplied for the configuration keys, they can be overwritten by explicitly declaring them. The pattern for these environment variables keys are:
MIBWORKERCONFIG_{WORKERNAME}_{KEY}
Where the worker's name is the name of the concrete worker class. So in our example that would be:
MIBWORKERCONFIG_CONCRETEWORKER_{KEY}
The name of the worker can be customized by annotating the class with MibWorkerDescriptorAttribute
.
Configuration Keys
- InstancesCount (int): Number of instances to run. Default is
1
. - HeartbeatIntervalMilliseconds (int): Interval for heartbeat checks in milliseconds. Default is
10000
. - SilentUnhandledExceptions (bool): Default is
true
. Indicates whether unhandled exceptions should be propagated or supressed. Disabling this setting might cause the host to stop if exceptions are left unhandled.
4. Configure the WorkerService
Create a WorkerService project and use the extension methods below to register the Mib Workers.
using MediaiBox.Workers.Extensions;
var builder = Host.CreateApplicationBuilder(args);
builder.ConfigureMibWorkerService();
builder.AddMibWorker<ConcreteWorker>();
var host = builder.Build();
host.Run();
Here is what is going on step by step:
builder.ConfigureMibWorkerService()
Configures theHostApplicationBuilder
to ensure that the MibWorker services are managed efficiently. This is achieved by:Configuring HostOptions
HostOptions.ServicesStartConcurrently
: Set to true to allow workers to start concurrently.HostOptions.ServicesStopConcurrently
: Set to true to allow workers to stop concurrently.HostOptions.BackgroundServiceExceptionBehavior
: Set to prevent the host from keep running if any MibWorker were to die.
Configuring additional services
MibWorkerServiceLifecycleLogger
: Adds a hosted service that logs the lifecycle events of MibWorker services.
builder.AddMibWorker<ConcreteWorker>()
Adds N instances of the given worker implementation as Hosted Service to theHostApplicationBuilder
. The number of instances is read from the MibWorkerConfig.
5. Execute and amaze yourself
Run the application and see the workers come to life.