Hangfire 学习笔记

更新 2022-04-05

看这篇 ASP.NET Core Library – Hangfire

 

更新 : 2018-10-29

在 asp.net core 使用 hangfire 也很不错哦

startup.cs

services.AddHangfire(config => config.UseSqlServerStorage(connectionString)); 

public class HangfireActivator : JobActivator
{
    private readonly IServiceProvider ServiceProvider;

    public HangfireActivator(IServiceProvider serviceProvider)
    {
        ServiceProvider = serviceProvider;
    }

    public override object ActivateJob(Type type)
    {
        return ServiceProvider.GetService(type);
    }
}

GlobalConfiguration.Configuration.UseActivator(new HangfireActivator(serviceProvider)); // 依赖注入
appBuilder.UseHangfireServer();
// local run 才有, 因为我没有弄 authen, 我看而已嘛 
if (hostingEnvironment.IsDevelopment())
{
    appBuilder.UseHangfireDashboard();
}

task 

public class CleanImageService 
{
      
    private IHostingEnvironment HostingEnvironment;

    public CleanImageService(
          
        IHostingEnvironment hostingEnvironment
    ) {
     
        HostingEnvironment = hostingEnvironment;
    }
                
    [AutomaticRetry(Attempts = 0, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
    public async Task CleanImage()
    {
          
    }
}

startup 时启动

  RecurringJob.AddOrUpdate<CleanImageService<ApplicationDbContext>>(c => c.CleanImage(), Cron.Daily(0, 0));

 

note : retry 没有方法设置间隔,hangfire 设计是下一分钟就会马上 retry 了.

 

 

 

 

更新 : 2017-04-23 

cron refer : https://crontab.guru

hangfire 支持 Cron 表达式 (熟悉 linux 应该懂)。hangfire 使用 NCrontab 库, 它支持 .NET Standard (.net framework, .net core 等等)

hangfire 有个 Dashboard 页面管理任务, 通过 Hangfire.Dashboard.Authorization 可以设定页面权限. 

hangfire 支持 autoretry 

hangfire 会把任务参数存入数据库中 

如果 server down 错过了任务执行的时段, hangfire 会在 server up 时马上运行相关任务 ( 如果你不希望这样的话...我也没法关掉../.\ )

在设计任务时,要想想这些问题 : 

-如果任务出错了怎么办 (也考虑 一半成功一半不成功的情况) ?

-如果你 autoretry 但是出现 double job 怎么办 ? (比如客户收到 2 封同样的邮件) 

-如果 miss 怎么办? (server 在指定时间没有跑,在重启后另外一个时间上跑的可以接受吗 ? )

下面这个代码可以确认运行时的时间和 Cron 表达式是否匹配. 

var date = new DateTime(2018, 1, 1, 10, 10, 00);
var s = CrontabSchedule.Parse("10 * * * *");
var start = date.AddMinutes(-1);
var end = date.AddSeconds(1);
IEnumerable<DateTime> occurrences = s.GetNextOccurrences(start, end).ToList();
if (occurrences.Count() >= 1)
{
    // right time                            
}
else
{
    // miss time 
}

 

 

2017-03-16 

有时候我们会想让服务端运行一些非常小的程序,比如当用户下订单后,要发一封 email 通知管理人员。

这个发 email 消耗的时间不应该让用户来承担,所以我们需要开启一个小小的 server task 来运行。

 

我们可以使用  HostingEnvironment.QueueBackgroundWorkItem 来完成

但是,这个是在 System.Web.Hosting 命名空间下的,.net core 就没得用了。

 

Hangfire 这个插件就可以派上用场了。

https://www.nuget.org/packages/HangFire/1.6.11 下载 

http://docs.hangfire.io/en/latest/quick-start.html 使用

它需要 sql 来运作哦,而且要记得在运行程序时,你是获取不到任何关于请求的资料了,因为这是完全独立的线程. 

 

posted @ 2017-03-16 18:00  兴杰  阅读(1907)  评论(0编辑  收藏  举报