Hangfire Background Worker Manager
Hangfire is an advanced background jobs and worker manager. You can integrate Hangfire with the ABP Framework to use it instead of the default background worker manager.
The major advantage is that you can use the same server farm to manage your Background Jobs and Workers, as well as leverage the advanced scheduling that is available from Hangfire for Recurring Jobs, aka Background Workers.
Installation
It is suggested to use the ABP CLI to install this package.
Using the ABP CLI
Open a command line window in the folder of the project (.csproj file) and type the following command:
Manual Installation
If you want to manually install;
Add the Volo.Abp.BackgroundWorkers.Hangfire NuGet package to your project:
Install-Package Volo.Abp.BackgroundWorkers.Hangfire
Add the
AbpBackgroundWorkersHangfireModule
to the dependency list of your module:
Hangfire background worker integration provides an adapter
HangfirePeriodicBackgroundWorkerAdapter
to automatically load anyPeriodicBackgroundWorkerBase
andAsyncPeriodicBackgroundWorkerBase
derived classes asIHangfireBackgroundWorker
instances. This allows you to still to easily switch over to use Hangfire as the background manager even you have existing background workers that are based on the default background workers implementation.
Configuration
You can install any storage for Hangfire. The most common one is SQL Server (see the Hangfire.SqlServer NuGet package).
After you have installed these NuGet packages, you need to configure your project to use Hangfire.
1.First, we change the Module
class (example: <YourProjectName>HttpApiHostModule
) to add Hangfire configuration of the storage and connection string in the ConfigureServices
method:
You have to configure a storage for Hangfire.
- If you want to use hangfire's dashboard, you can add
UseAbpHangfireDashboard
call in theOnApplicationInitialization
method inModule
class
Create a Background Worker
HangfireBackgroundWorkerBase
is an easy way to create a background worker.
- RecurringJobId Is an optional parameter, see Hangfire document
- CronExpression Is a CRON expression, see CRON expression
You can directly implement the
IHangfireBackgroundWorker
, butHangfireBackgroundWorkerBase
provides some useful properties like Logger.
UnitOfWork
Register BackgroundWorkerManager
After creating a background worker class, you should add it to the IBackgroundWorkerManager
. The most common place is the OnApplicationInitializationAsync
method of your module class:
context.AddBackgroundWorkerAsync(...)
is a shortcut extension method for the expression below:
So, it resolves the given background worker and adds to the IBackgroundWorkerManager
.
While we generally add workers in OnApplicationInitializationAsync
, there are no restrictions on that. You can inject IBackgroundWorkerManager
anywhere and add workers at runtime. Background worker manager will stop and release all the registered workers when your application is being shut down.