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

问题描述 投票:5回答:3

我有一些服务,有一些方法,我想重复工作。

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

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

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

也许我应该将一些cron值放到appsettings.json中?

c# .net asp.net-mvc asp.net-core hangfire
3个回答
-2
投票

我玩的篝火的缺点是设置它的复杂性。它需要很少的额外表来设置它才能工作。我希望你在数据库中为它创建表。请看看如何获​​得经常性的工作.- HangFire recurring task data。我觉得排队工作或后台工作非常好,但对于经常性的工作,我建议去Quartz.net。它不需要这样的设置,也很容易集成。到目前为止没有问题,它有很好的CRON支持。示例 - https://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net


5
投票

你的意思是这样的吗?

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

0
投票

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

您绝对可以在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在Startup类的Configure方法中使用您的自定义实现。

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

Hangfire Documentation上阅读更多信息

© www.soinside.com 2019 - 2024. All rights reserved.