Duplicate Jobs with Hangfire and Asp.Net Core

I have a serivce that has some kind of method that I would like to repeat.

I know that I can use hangfire in my Startup.cs, for example:

RecurringJob.AddOrUpdate(() => Console.WriteLine("I'm a recurring job"), Cron.Minutely);

But the question is, how can I use my services here? Should I use somehow (dependency injection?) Or elsewhere?

Maybe you need to put some cron values ​​in appsettings.json?

+4
source share
3 answers

- ?

RecurringJob.AddOrUpdate<IAlertService>(x => 
    x.SendAlerts(emailSettings, link), Cron.MinuteInterval(1));
+2

, - Hangfire, , , , .

Dependency Injection Hangfire .

JobActivator ActivateJob(Type), IServiceProvider.

public class DependencyJobActivator : JobActivator
{
    private readonly IServiceProvider _serviceProvider;

    public DependencyJobActivator(IServiceProvider serviceProvider)
    { 
        _serviceProvider = serviceProvider;
    }

    public override object ActivateJob(Type jobType) {
        return _serviceProvider.GetService(jobType);
    }
}

Hangfire "Configure" "".

public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
    app.UseHangfireDashboard();
    app.UseHangfireServer(new BackgroundJobServerOptions { Activator = new DependencyJobActivator(serviceProvider) });
    app.UseMvc();
}

, Hangfire

0

Source: https://habr.com/ru/post/1668980/


All Articles