From 798da7473c264c28b6b15026fe2dca8a39406898 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20=C3=87otur?= Date: Wed, 4 Mar 2020 15:54:30 +0300 Subject: [PATCH] Create Background-Workers.md --- docs/en/Background-Workers.md | 83 +++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 docs/en/Background-Workers.md diff --git a/docs/en/Background-Workers.md b/docs/en/Background-Workers.md new file mode 100644 index 0000000000..22e7c66e4d --- /dev/null +++ b/docs/en/Background-Workers.md @@ -0,0 +1,83 @@ +# Background Workers + +## Introduction + +Background workers are used to execute some tasks in the background. You may need background workers for several reasons. + +### Create a Background Worker + +A background worker is a class that derives from the `AsyncPeriodicBackgroundWorkerBase` or `PeriodicBackgroundWorkerBase` class. Both base classes are derived from `ISingletonDependency`. + +### Status Checker +This example is used to simple check remote application status. Just suppose that, we want to check and store some web applications are running or not? + +````csharp +public class AppStatusService : ITransientDependency +{ + . + . + public void CheckAppStatus() + { + var ping = new System.Net.NetworkInformation.Ping(); + + var result = ping.Send("www.google.com"); + + // save the result + } + . + . +} +```` + +Then create a background worker class that derived from the `PeriodicBackgroundWorkerBase`: + +````csharp +. +. +using Volo.Abp.BackgroundWorkers; + +namespace Volo.Www.Application +{ + public class AppStatusCheckingWorker : PeriodicBackgroundWorkerBase + { + private readonly IAppStatusService _appStatusService; + + public AppStatusCheckingWorker( + AbpTimer timer, + IServiceScopeFactory scopeFactory, + IAppStatusService appStatusService) + : base(timer, scopeFactory) + { + _appStatusService = appStatusService; + Timer.Period = 10_000; // 10 secs + } + + protected override void DoWork(PeriodicBackgroundWorkerContext workerContext) + { + _appStatusService.CheckAppStatus(); + } + } +} +```` + +This worker will call DoWorkAsync() method every 10 seconds while the application is running. + +### Configuration + +Add your BackgroundWorker at `OnApplicationInitialization` in your [module class](Module-Development-Basics.md). The example below initialize the background worker to your module: + +````csharp +using Volo.Abp.BackgroundWorkers; + +public class MyModule : AbpModule +{ + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + context.ServiceProvider + .GetRequiredService() + .Add( + context.ServiceProvider.GetRequiredService() + ); + } +} +```` \ No newline at end of file