Delegate job to worker (api Feature)
This file explains what to use the the delegate job to worker feature in your V3 project.
Prerequisite
Knowledge to have:
- Hangfire
- JobMonitor Project
Database:
- The hangfire database is generally initialized by the JobMonitor project
- The connection string to this database is configured in the bianetconfig.[Env].json files (see Activation chapter)
Overview
- When a controller is called it can create a task that is run asynchronously on the worker service server.
- It is a smart way to not slow the front server, when the task is long.
- It can be use to treat huge file or do complex calculation.
Activation
- bianetconfig.json In the BIANet Section add:
"ApiFeatures": {
"DelegateJobToWorker": {
"Activate": true,
"ConnectionStringName": "[YourAppConnectionStringName]"
}
},
replace [YourAppConnectionStringName] by the name of your connection string in appsettings.json
Usage
Create the job
In the Application layer (this layer is share with the worker service) create the job class in the Job folder.
namespace [YourCompanyName].[YourProjectName].Application.Job
{
using System;
using BIA.Net.Core.Application.Helpers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
/// <summary>
/// Sample class to use a hangfire task.
/// </summary>
[BIAQueueAttribute]
public class TestHangfire
{
/// <summary>
/// Initializes a new instance of the <see cref="TestHangfire"/> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <param name="logger">logger.</param>
public TestHangfire(IConfiguration configuration, ILogger<TestHangfire> logger)
{
this.Configuration = configuration;
this.Logger = logger;
}
/// <summary>
/// application Configuration.
/// </summary>
protected IConfiguration Configuration { get; }
/// <summary>
/// application logger.
/// </summary>
protected ILogger Logger { get; }
/// <summary>
/// Run the processes that are waiting.
/// </summary>
public void RunWaitingProcess()
{
this.Logger.LogInformation($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}: TestHangfire => This log is generated by a hangfire task");
}
}
}
Call the job
In the Presentation.Api layer add the package Hangfire 1.7.18 (respect the version to keep a database compatibility)
You can call the job like that from a controller:
using BIA.Net.Core.Application.Helpers;
...
using Hangfire;
using Hangfire.States;
...
var client = new BackgroundJobClient();
client.Create<TestHangfire>(x => x.RunWaitingProcess(), new EnqueuedState(BIAQueueAttribute.QueueName));