ASP.NET Core 3.1 系列之 Web API 添加定时任务Hangfire

ASP.NET Core 3.1 系列之 Web API 中间件篇 (三)

定时任务(Hangfire)MySQL数据库 使用教程
基础使用篇

前言

Hangfire不受特定.NET应用程序类型的限制。您可以在 ASP.NET Web应用程序 、非ASP.NET Web应用程序、控制台应用程序 或 Windows服务 中使用它。由持久存储支持。开源且免费用于商业用途。

添加NuGet包

添加包:Hangfire.AspNetCore

在这里插入图片描述
添加包:Hangfire.MySqlStorage

在这里插入图片描述

配置

修改 appsettings.json 配置文件

  "ConnectionStrings": {
    "HangfireConnection": "Server=localhost;Port=3306;Database=ForceDemo;Uid=root;Pwd=123456;CharSet=utf8mb4;"
  }

修改 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
	//Hangfire配置
    services.AddHangfire(conf => conf.UseStorage(new MySqlStorage(Configuration.GetConnectionString("HangfireConnection"), new MySqlStorageOptions { TablesPrefix = "job_" })));
    //Hangfire
    services.AddHangfireServer(x => new BackgroundJobServerOptions
    {
          ServerName = string.Format("{0}.{1}", Environment.MachineName, Guid.NewGuid().ToString())
    });
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
         app.UseDeveloperExceptionPage();
    }
	//Hangfire 仪表盘
	//访问地址 http://localhost:5000/hangfire
    app.UseHangfireDashboard();

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
         endpoints.MapControllers();
    });
}

使用

示例代码:

[HttpGet("GetHangfireTest")]
public IActionResult GetHangfireTest()
{
    BackgroundJob.Enqueue(() => Console.WriteLine("队列任务"));

    BackgroundJob.Schedule(() => Console.WriteLine("延后2分钟"), TimeSpan.FromMinutes(2));

    RecurringJob.AddOrUpdate(() => Console.WriteLine("每分钟执行一下"), Cron.Minutely());

    return Ok();
}

Hangfire 官网

更多中间件使用教程

【身份验证(Jwt)使用教程 】

【日志(Log4Net)使用教程 】

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

隔壁程序员有话说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值