mirror of https://github.com/abpframework/abp.git
Browse Source
* Send IServiceProvider to DoWork method of the periodic background worker #2539 * Introduce AsyncPeriodicBackgroundWorkerBase #2540pull/2545/head
8 changed files with 137 additions and 64 deletions
@ -1,7 +1,9 @@ |
|||||
namespace Volo.Abp.BackgroundJobs |
using System.Threading.Tasks; |
||||
|
|
||||
|
namespace Volo.Abp.BackgroundJobs |
||||
{ |
{ |
||||
public interface IBackgroundJobExecuter |
public interface IBackgroundJobExecuter |
||||
{ |
{ |
||||
void Execute(JobExecutionContext context); |
Task ExecuteAsync(JobExecutionContext context); |
||||
} |
} |
||||
} |
} |
||||
@ -0,0 +1,55 @@ |
|||||
|
using System; |
||||
|
using System.Threading; |
||||
|
using System.Threading.Tasks; |
||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using Microsoft.Extensions.Logging; |
||||
|
using Volo.Abp.Threading; |
||||
|
|
||||
|
namespace Volo.Abp.BackgroundWorkers |
||||
|
{ |
||||
|
public abstract class AsyncPeriodicBackgroundWorkerBase : BackgroundWorkerBase |
||||
|
{ |
||||
|
protected IServiceScopeFactory ServiceScopeFactory { get; } |
||||
|
protected AbpTimer Timer { get; } |
||||
|
|
||||
|
protected AsyncPeriodicBackgroundWorkerBase( |
||||
|
AbpTimer timer, |
||||
|
IServiceScopeFactory serviceScopeFactory) |
||||
|
{ |
||||
|
ServiceScopeFactory = serviceScopeFactory; |
||||
|
Timer = timer; |
||||
|
Timer.Elapsed += Timer_Elapsed; |
||||
|
} |
||||
|
|
||||
|
public override async Task StartAsync(CancellationToken cancellationToken = default) |
||||
|
{ |
||||
|
await base.StartAsync(cancellationToken).ConfigureAwait(false); |
||||
|
Timer.Start(cancellationToken); |
||||
|
} |
||||
|
|
||||
|
public override async Task StopAsync(CancellationToken cancellationToken = default) |
||||
|
{ |
||||
|
Timer.Stop(cancellationToken); |
||||
|
await base.StopAsync(cancellationToken).ConfigureAwait(false); |
||||
|
} |
||||
|
|
||||
|
private void Timer_Elapsed(object sender, System.EventArgs e) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
using (var scope = ServiceScopeFactory.CreateScope()) |
||||
|
{ |
||||
|
AsyncHelper.RunSync( |
||||
|
() => DoWorkAsync(new PeriodicBackgroundWorkerContext(scope.ServiceProvider)) |
||||
|
); |
||||
|
} |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
Logger.LogException(ex); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
protected abstract Task DoWorkAsync(PeriodicBackgroundWorkerContext workerContext); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,14 @@ |
|||||
|
using System; |
||||
|
|
||||
|
namespace Volo.Abp.BackgroundWorkers |
||||
|
{ |
||||
|
public class PeriodicBackgroundWorkerContext |
||||
|
{ |
||||
|
public IServiceProvider ServiceProvider { get; } |
||||
|
|
||||
|
public PeriodicBackgroundWorkerContext(IServiceProvider serviceProvider) |
||||
|
{ |
||||
|
ServiceProvider = serviceProvider; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue