参考文章Hangfire定时任务 - 北落师门、 - 博客园 (cnblogs.com)

如果要使用SqlService直接按照参考文章操作即可

NuGet包

<PackageReference Include="Hangfire" Version="1.8.14" />//HangFile必要的包
	<PackageReference Include="Hangfire.HttpJob" Version="3.8.5" />//仪表盘
	<PackageReference Include="Hangfire.Dashboard.BasicAuthorization" Version="1.0.2" />
	<PackageReference Include="Hangfire.MySqlStorage" Version="2.0.3" />//使用MySql

操作

数据库

需要提前创建一个名为HangfireText的数据库,其中的表是自动生成的

HangFire定时调度(Mysql版本)_定时任务

appsettings.json文件

需要定义一个连接你mysql数据库的字符串,由于我的vs无法生成连接mysql的字符串所以手写一个

"ConnectionStrings": {
   "MySQLConnection": "server=.;port=3306;uid=root;pwd=123456;database=hangfireText;Connect Timeout=20;" 
 },//Connect Timeout=20为连接超时时间

Program.cs文件注册(.net 5请去Starup.cs中设置)

因为需要读取配置文件,所以需要定义一个var Config = builder.Configuration;

var Config = builder.Configuration;
builder.Services.AddHangfire(configuration => configuration
	.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
	.UseSimpleAssemblyNameTypeSerializer()
	.UseRecommendedSerializerSettings()
	.UseStorage(new MySqlStorage(
		Config["ConnectionStrings:MySQLConnection"],
		new MySqlStorageOptions
		{
			TransactionIsolationLevel = IsolationLevel.ReadCommitted,
			QueuePollInterval = TimeSpan.FromSeconds(15),
			JobExpirationCheckInterval = TimeSpan.FromHours(1),
			CountersAggregateInterval = TimeSpan.FromMinutes(5),
			PrepareSchemaIfNecessary = true,
			DashboardJobListLimit = 50000,
			TransactionTimeout = TimeSpan.FromMinutes(1),
			TablesPrefix = "Hangfire"
		})).UseHangfireHttpJob());
builder.Services.AddHangfireServer();//必须加,不加无法执行
//app
///Hangfire为路径
app.UseHangfireDashboard("/Hangfire", new DashboardOptions
{
	Authorization = new[] {new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
{
RequireSsl =false,
SslRedirect =false,
LoginCaseSensitive = true,
Users = new[]
{
//授权登录
new BasicAuthAuthorizationUser
{
Login ="admin",
PasswordClear = "123456",
}
}
})}
});

app.UseRouting();

运行成功

HangFire定时调度(Mysql版本)_定时任务_02

仪表盘核心功能,可以添加作业,周期性运行作业

通过cron表达式来给每一个作业添加周期

cron表达式网址 cron.ciding.cc

如果点击进入页面报错

HangFire定时调度(Mysql版本)_定时任务_03

解决方案为:连接字符串加入allowuservariables=True;

server=10.31.52.8;port=3306;uid=root;pwd=123456;database=hangfiretext;Connect Timeout=20;allowuservariables=True

HangFire定时调度(Mysql版本)_定时任务_04

加入定时任务则变成

HangFire定时调度(Mysql版本)_定时任务_05