简体   繁体   中英

Recurring jobs with Hangfire and Asp.Net Core

I have serivce which has some method which I would like to be Recurring job.

I know that I can use hangfire in my Startup.cs eg:

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 here (dependency injection ?) or in the other place?

Maybe should I put some cron values to the appsettings.json ?

Do you mean something like this?

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

Here is how you can call service for hangfire from startup file. In my case, I have IMediator as constructor of my service. You may have one or more other which you can add in AddTransient.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages()
            .AddRazorRuntimeCompilation()
            .AddMvcOptions(options => options.EnableEndpointRouting = false);
    
         serviceCollection.AddTransient<INotificationSchedulerService>
        (
           serviceProvider => new NotificationSchedulerService
           (
               serviceProvider.GetService<IMediator>()
           )
        );
      
          services.AddHangfire(x => x.UseSqlServerStorage("Server=SQLEx\\SQLSERVER2019;Database=Tempdatabase;User ID=sa;Password=xuz@de5234;MultipleActiveResultsets=true"));
        services.AddHangfireServer();
    }

    public void Configure(IApplicationBuilder applicationBuilder, IWebHostEnvironment hostEnvironment)
    { 
         RecurringJob.AddOrUpdate<INotificationSchedulerService>(x => x.ScheduleLikeNotifications(),"*/2 * * * *");
    }
}

I am a year late to this party, and stumbled across this question whilst looking for something Hangfire related, figured I would answer as there is no answer to the question being asked.

You absolutely can use Dependency Injection in Hangfire without having to rely on default constructors or instantiating within your class.

You can inherit from JobActivator and override the ActivateJob(Type) method, while your custom implementation uses the 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);
    }
}

Then simply tell Hangfire to use your custom implementation in the Startup class' Configure method.

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

Read more here on the Hangfire Documentation

The downside of hangfire I fet was the complexity in the setting it up. It needs few extra tables to set up for it to work. I hope you have the tables created for it in your database. Pls see this how to get the recurring jobs.- HangFire recurring task data . I feel it is very good for queuing jobs or for background tasks but for recurring jobs, I would suggest to go for Quartz.net . It needs no such setting up and very easy to integrate. No problems so far and it has good CRON support. Example - https://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM