创建 Hangfire 定时任务项目

发布时间 2023-10-05 09:45:26作者: 宁静致远.

创建 ASP.NET Core Web 应用程序

 使用 NuGet 安装 Hangfire 依赖程序包

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Hangfire.AspNetCore" Version="1.8.5" />
    <PackageReference Include="Hangfire.Core" Version="1.8.5" />
    <PackageReference Include="Hangfire.SqlServer" Version="1.8.5" />
    <PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.1" />
  </ItemGroup>

</Project>

创建数据库

CREATE DATABASE [HangfireTest]
GO

打开 appsettings.json 配置数据库连接字符串

 

 "ConnectionStrings": {
    "HangfireConnection": "Server=DESKTOP-DABHN6U\\MSSQLSERVER2014;uid=sa;pwd=123456;database=HangfireTest;MultipleActiveResultSets=true;TrustServerCertificate=true;"
  },

注册服务,打开 Program.cs 文件

 var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddRazorPages();

            builder.Services.AddHangfire(configuration => configuration
        .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
        .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
        .UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection")));

            builder.Services.AddHangfireServer();

            var app = builder.Build();

同时添加仪表板 UI

  app.UseHangfireDashboard();
            BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
            RecurringJob.AddOrUpdate(
     "myrecurringjob",
    () => Console.WriteLine("重复执行!"),
     Cron.Minutely);

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapHangfireDashboard();

运行应用程序

运行后数据库表自动创建

 查看后台作业

https://localhost:7282/hangfire

 

 引用:https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html 

 官方网站:https://www.hangfire.io/ 

  

 

 

//支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者。
var jobId = BackgroundJob.Enqueue(()=>WriteLog("队列任务执行了!"));

//延迟任务执行:不是马上调用方法,而是设定一个未来时间点再来执行,延迟作业仅执行一次
var jobId = BackgroundJob.Schedule(()=>WriteLog("一天后的延迟任务执行了!"),TimeSpan .FromDays(1));//一天后执行该任务

//循环任务执行:一行代码添加重复执行的任务,其内置了常见的时间循环模式,也可基于CRON表达式来设定复杂的模式。【用的比较的多】
RecurringJob.AddOrUpdate(()=>WriteLog("每分钟执行任务!"), Cron.Minutely); //注意最小单位是分钟

//延续性任务执行:类似于.NET中的Task,可以在第一个任务执行完之后紧接着再次执行另外的任务
BackgroundJob.ContinueWith(jobId,()=>WriteLog("连续任务!"));