使用 Hangfire 和 Asp.Net Core 的重复性工作

Recurring jobs with Hangfire and Asp.Net Core

我有一些服务,其中有一些我想成为重复工作的方法。

我知道我可以在 Startup.cs 中使用 hangfire,例如:

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

但问题是我如何在这里使用我的服务?我应该在这里使用某种方式(依赖注入?)还是在其他地方使用?

也许我应该将一些 cron 值添加到 appsettings.json?

我发现 hangfire 的缺点是设置它的复杂性。它需要一些额外的表来设置它才能工作。我希望你在你的数据库中为它创建了表。请查看如何获得重复性工作。- 。我觉得它非常适合排队作业或后台任务,但对于重复作业, 我建议选择 Quartz.net。它不需要这样的设置并且非常容易集成。到目前为止没有问题,它有很好的 CRON 支持。示例 - https://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net

你的意思是这样的吗?

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

我参加这个聚会晚了一年,在寻找与 Hangfire 相关的东西时偶然发现了这个问题,我想我会回答,因为所问的问题没有答案。

你绝对可以在 Hangfire 中使用依赖注入,而不必依赖默认构造函数或在你的 class.

中实例化

您可以继承 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 在 Startup class' Configure 方法中使用您的自定义实现。

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

Hangfire Documentation

上阅读更多内容

以下是如何从启动文件调用 hangfire 服务。就我而言,我将 IMediator 作为我服务的构造函数。您可能有一个或多个可以添加到 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 * * * *");
    }
}