Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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 ?

like image 936
mskuratowski Avatar asked Feb 06 '17 21:02

mskuratowski


2 Answers

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 * * * *");
    }
}
like image 67
prisan Avatar answered Nov 06 '22 09:11

prisan


Do you mean something like this?

RecurringJob.AddOrUpdate<IAlertService>(x => 
    x.SendAlerts(emailSettings, link), Cron.MinuteInterval(1));
like image 26
SpruceMoose Avatar answered Nov 06 '22 08:11

SpruceMoose