.net core 调度任务 HangFire
官方文档
Deployment to Production — Hangfire Documentation
nuget
Hangfire.AspNetCore
Hangfire.MySqlStorage
我使用的是mysql 同时hangfire也支持sqlserver 所以他可以持久化
1 using Hangfire;
2 using Hangfire.MySql;
3 using HangFire;
4 using System.Transactions;
5
6 var builder = WebApplication.CreateBuilder(args);
7 builder.Services.AddHangfire(options =>
8 {
9 string hangFireConStr = builder.Configuration.GetSection("hangFireConStr").Value;
10 options.UseStorage(new MySqlStorage(hangFireConStr, new MySqlStorageOptions
11 {
12 TransactionIsolationLevel = IsolationLevel.ReadCommitted,//TransactionIsolationLevel - 事务隔离级别。默认值为已提交读取。
13 QueuePollInterval = TimeSpan.FromSeconds(15), //QueuePollInterval - 作业队列轮询间隔。默认值为 15 秒。
14 JobExpirationCheckInterval = TimeSpan.FromHours(1), //JobExpirationCheckInterval - 作业过期检查间隔(管理过期记录)。默认值为 1 小时。
15 CountersAggregateInterval = TimeSpan.FromMinutes(5), //CountersAggregateInterval - 聚合计数器的间隔。默认值为 5 分钟。
16 PrepareSchemaIfNecessary = true, //PrepareSchemaIfNecessary - 如果设置为 ,则创建数据库表。默认值为 。truetrue
17 DashboardJobListLimit = 50000, //DashboardJobListLimit - 仪表板作业列表限制。默认值为 50000。
18 TransactionTimeout = TimeSpan.FromMinutes(1), //TransactionTimeout - 事务超时。默认值为 1 分钟。
19 TablesPrefix = "Hangfire" //TablesPrefix - 数据库中表的前缀。默认值为无
20 }));
21 });
22 //注入核心服务
23 builder.Services.AddHangfireServer();
24 //注入 hangfire 后台服务
25 builder.Services.AddHostedService<RecurringJobsService>();
26 // Add services to the container.
27
28 builder.Services.AddControllers();
29 // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
30 builder.Services.AddEndpointsApiExplorer();
31 builder.Services.AddSwaggerGen();
32
33 var app = builder.Build();
34 //hangfire面板
35 app.UseHangfireDashboard();
36 // Configure the HTTP request pipeline.
37 if (app.Environment.IsDevelopment())
38 {
39 app.UseSwagger();
40 app.UseSwaggerUI();
41 }
42
43 app.UseHttpsRedirection();
44
45 app.UseAuthorization();
46
47 app.MapControllers();
48
49 app.Run();
后台任务
1 using Hangfire;
2 using Hangfire.Server;
3 using System.Diagnostics.CodeAnalysis;
4
5 namespace HangFire
6 {
7 public class RecurringJobsService : BackgroundService
8 {
9 private readonly IBackgroundJobClient _backgroundJobs;
10 private readonly IRecurringJobManager _recurringJobs;
11 private readonly ILogger<RecurringJobScheduler> _logger;
12 public RecurringJobsService(
13 [NotNull] IBackgroundJobClient backgroundJobs,
14 [NotNull] IRecurringJobManager recurringJobs,
15 [NotNull] ILogger<RecurringJobScheduler> logger)
16 {
17 _backgroundJobs = backgroundJobs ?? throw new ArgumentNullException(nameof(backgroundJobs));
18 _recurringJobs = recurringJobs ?? throw new ArgumentNullException(nameof(recurringJobs));
19 _logger = logger ?? throw new ArgumentNullException(nameof(logger));
20 }
21
22 protected override Task ExecuteAsync(CancellationToken stoppingToken)
23 {
24 try
25 {
26 //_backgroundJobs.Enqueue<Services>(x => x.LongRunning(JobCancellationToken.Null));
27
28 _recurringJobs.AddOrUpdate("seconds", () => Console.WriteLine("Hello, seconds!"), "*/15 * * * * *");
29 _recurringJobs.AddOrUpdate("minutely", () => Console.WriteLine("Hello, world!"), Cron.Minutely);
30 _recurringJobs.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), "25 15 * * *");
31 _recurringJobs.AddOrUpdate("neverfires", () => Console.WriteLine("Can only be triggered"), "0 0 31 2 *");
32 _recurringJobs.AddOrUpdate("Hawaiian", () => Console.WriteLine("Hawaiian"), "15 08 * * *", TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time"));
33 _recurringJobs.AddOrUpdate("UTC", () => Console.WriteLine("UTC"), "15 18 * * *");
34 _recurringJobs.AddOrUpdate("Russian", () => Console.WriteLine("Russian"), "15 21 * * *", TimeZoneInfo.Local);
35 }
36 catch (Exception e)
37 {
38 _logger.LogError(e, "An exception occurred while creating recurring jobs.");
39 }
40
41 return Task.CompletedTask;
42 }
43 }
44 }
测试运行

面板 默认路径是hangfire

数据库相关的表

浙公网安备 33010602011771号