Recurring jobs with Hangfire and Asp.Net Core
Asked Answered
M

4

13

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 e.g:

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 ?

Mulloy answered 6/2, 2017 at 21:42 Comment(2)
RecurringJob.AddOrUpdate("MyMethodNameAsID", () => Class.Method(), Cron.Minutely); I think would work... Maybe. If I understood your question correctly.Gabbard
@Gabbard Yeah, It's working, but insted of that code I would like to use my serviceMulloy
B
-8

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

Biyearly answered 7/2, 2017 at 4:29 Comment(1)
Yes, but I would like to use hangfire and I'm looking for sollution how can I do this.Mulloy
Q
17

Do you mean something like this?

RecurringJob.AddOrUpdate<IAlertService>(x => 
    x.SendAlerts(emailSettings, link), Cron.MinuteInterval(1));
Qualitative answered 21/2, 2017 at 21:36 Comment(0)
U
4

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 * * * *");
    }
}
Upkeep answered 18/3, 2021 at 6:54 Comment(0)
H
1

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

Holloman answered 3/3, 2018 at 20:11 Comment(1)
I tested this, then removed the activator and yet all my services still get injected correctly. I believe the activator is no longer required (but used to be, as yours isn't the only answer suggesting this).Schist
B
-8

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

Biyearly answered 7/2, 2017 at 4:29 Comment(1)
Yes, but I would like to use hangfire and I'm looking for sollution how can I do this.Mulloy

© 2022 - 2024 — McMap. All rights reserved.