当前位置: 代码网 > it编程>编程语言>Asp.net > 使用Hangfire+.NET 6实现定时任务管理(推荐)

使用Hangfire+.NET 6实现定时任务管理(推荐)

2024年05月18日 Asp.net 我要评论
在.net开发生态中,我们以前开发定时任务都是用的quartz.net完成的。在这篇文章里,记录一下另一个很强大的定时任务框架的使用方法:hangfire。两个框架各自都有特色和优势,可以根据参考文章

在.net开发生态中,我们以前开发定时任务都是用的quartz.net完成的。在这篇文章里,记录一下另一个很强大的定时任务框架的使用方法:hangfire。两个框架各自都有特色和优势,可以根据参考文章里张队的那篇文章对两个框架的对比来进行选择。

引入nuget包和配置

引入hangfire相关的nuget包:

hangfire.aspnetcore
hangfire.memorystorage
hangfire.dashboard.basic.authentication

并对hangfire进行服务配置:

builder.services.addhangfire(c =>
{
    // 使用内存数据库演示,在实际使用中,会配置对应数据库连接,要保证该数据库要存在
    c.usememorystorage();
});

// hangfire全局配置
globalconfiguration.configuration
    .usecolouredconsolelogprovider()
    .useseriloglogprovider()
    .usememorystorage()
    .withjobexpirationtimeout(timespan.fromdays(7));

// hangfire服务器配置
builder.services.addhangfireserver(options =>
{
    options.heartbeatinterval = timespan.fromseconds(10);
});

使用hangfire中间件:

// 添加hangfire dashboard
app.usehangfiredashboard();
app.useauthorization();

app.mapcontrollers();

// 配置hangfire dashboard路径和权限控制
app.maphangfiredashboard("/hangfire", new dashboardoptions
{
    apppath = null,
    dashboardtitle = "hangfire dashboard test",
    authorization = new []
    {
        new hangfirecustombasicauthenticationfilter
        {
            user = app.configuration.getsection("hangfirecredentials:username").value,
            pass = app.configuration.getsection("hangfirecredentials:password").value
        }
    }
});

对应的配置如下:

appsettings.json
"hangfirecredentials": {
  "username": "admin",
  "password": "admin@123"
}

编写job

hangfire免费版本支持以下类型的定时任务:

  • 周期性定时任务:recurring job
  • 执行单次任务:fire and forget
  • 连续顺序执行任务:continouus job
  • 定时单次任务:schedule job

fire and forget

这种类型的任务一般是在应用程序启动的时候执行一次结束后不再重复执行,最简单的配置方法是这样的:

using hangfire;
backgroundjob.enqueue(() => console.writeline("hello world from hangfire with fire and forget job!"));

continuous job

这种类型的任务一般是进行顺序型的任务执行调度,比如先完成任务a,结束后执行任务b:

var jobid = backgroundjob.enqueue(() => console.writeline("hello world from hangfire with fire and forget job!"));
// continuous job, 通过指定上一个任务的id来跟在上一个任务后执行
backgroundjob.continuejobwith(jobid, () => console.writeline("hello world from hangfire using continuous job!"));

scehdule job

这种类型的任务是用于在未来某个特定的时间点被激活运行的任务,也被叫做delayed job

var jobid = backgroundjob.enqueue(() => console.writeline("hello world from hangfire with fire and forget job!"));

// continuous job, 通过指定上一个任务的id来跟在上一个任务后执行
backgroundjob.continuejobwith(jobid, () => console.writeline("hello world from hangfire using continuous job!"));

recurring job

这种类型的任务应该是我们最常使用的类型,使用cron表达式来设定一个执行周期时间,每到设定时间就被激活执行一次。对于这种相对常见的场景,我们可以演示一下使用单独的类来封装任务逻辑:

ijob.cs

namespace hellohangfire;

public interface ijob
{
    public task<bool> runjob();
}

job.cs

using serilog;
namespace hellohangfire;
public class job : ijob
{
    public async task<bool> runjob()
    {
        log.information($"start time: {datetime.now}");
        // 模拟任务执行
        await task.delay(1000);
        log.information("hello world from hangfire in recurring mode!");
        log.information($"stop time: {datetime.now}");
        return true;
    }
}

program.cs中使用cron来注册任务:

builder.services.addtransient<ijob, job>();
// ...
var app = builder.build();
// ...
var jobservice = app.services.getrequiredservice<ijob>();
// recurring job
recurringjob.addorupdate("run every minute", () => jobservice.runjob(), "* * * * *");

run

控制台输出:

info: hangfire.backgroundjobserver[0]
      starting hangfire server using job storage: 'hangfire.memorystorage.memorystorage'
info: hangfire.backgroundjobserver[0]
      using the following options for hangfire server:
          worker count: 20
          listening queues: 'default'
          shutdown timeout: 00:00:15
          schedule polling interval: 00:00:15
info: hangfire.server.backgroundserverprocess[0]
      server b8d0de54-caee-4c5e-86f5-e79a47fad51f successfully announced in 11.1236 ms
info: hangfire.server.backgroundserverprocess[0]
      server b8d0de54-caee-4c5e-86f5-e79a47fad51f is starting the registered dispatchers: serverwatchdog, serverjobcancellationwatcher, expirationmanager, countersaggregator, worker, delayedjobscheduler, recurringjobscheduler...
info: hangfire.server.backgroundserverprocess[0]
      server b8d0de54-caee-4c5e-86f5-e79a47fad51f all the dispatchers started
hello world from hangfire with fire and forget job!
hello world from hangfire using continuous job!
info: microsoft.hosting.lifetime[14]
      now listening on: https://localhost:7295
info: microsoft.hosting.lifetime[14]
      now listening on: http://localhost:5121
info: microsoft.hosting.lifetime[0]
      application started. press ctrl+c to shut down.
info: microsoft.hosting.lifetime[0]
      hosting environment: development
info: microsoft.hosting.lifetime[0]
      content root path: /users/yu.li1/projects/asinta/net6demo/hellohangfire/hellohangfire/
[16:56:14 inf] start time: 02/25/2022 16:56:14
[16:57:14 inf] start time: 02/25/2022 16:57:14
[16:57:34 inf] hello world from hangfire in recurring mode!
[16:57:34 inf] stop time: 02/25/2022 16:57:34

通过配置的dashboard来查看所有的job运行的状况:

长时间运行任务的并发控制???

从上面的控制台日志可以看出来,使用hangfire进行周期性任务触发的时候,如果执行时间大于执行的间隔周期,会产生任务的并发。如果我们不希望任务并发,可以在配置并发数量的时候配置成1,或者在任务内部去判断当前是否有相同的任务正在执行,如果有则停止继续执行。但是这样也无法避免由于执行时间过长导致的周期间隔不起作用的问题,比如我们希望不管在任务执行多久的情况下,前后两次激活都有一个固定的间隔时间,这样的实现方法我还没有试出来。有知道怎么做的小伙伴麻烦说一下经验。

job filter记录job的全部事件

有的时候我们希望记录job运行生命周期内的所有事件,可以参考官方文档:using job filters来实现该需求

参考文章

关于hangfire更加详细和生产环境的使用,张队写过一篇文章:hangfire项目实践分享

到此这篇关于使用hangfire+.net 6实现定时任务管理的文章就介绍到这了,更多相关.net 定时任务管理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com