首页 > 技术文章 > .Net Core 3.1中使用Hangfire定时器

CodingStone 2020-04-28 16:29 原文

起因呢是公司需要定时服务,而我呢又是一个强迫症比较严重的人,比较喜欢统一管理,不是很喜欢传统的定时器脚本,所以就研究了Hangfire

Hangfire支持永久化存储也支持存储在内存中,建议mysql 用5.7版本,在5.6版本中会出现索引错误的问题

上代码 创建一个HangfireDispose配置类

public class HangfireDispose
{
#region HangFire配置
public HangfireDispose()
{

}

//这里使用了.NetCore 自带的缓存 也可以存储在Mysql里面需要改一下方法引用即可

public static IServiceCollection HangfireServices(IServiceCollection services, IConfiguration configuration)
{
return services.AddHangfire(x => x.UseStorage(new MemoryStorage(
new MemoryStorageOptions
{
JobExpirationCheckInterval = TimeSpan.FromHours(1), //- 作业到期检查间隔(管理过期记录)。默认值为1小时。
CountersAggregateInterval = TimeSpan.FromMinutes(5), //- 聚合计数器的间隔。默认为5分钟。
}
)));
}

/// <summary>
/// 配置账号模板信息 
/// </summary>
/// <returns></returns>
public static DashboardOptions HfDispose(IConfiguration configuration)
{

var filter = new BasicAuthAuthorizationFilter(
new BasicAuthAuthorizationFilterOptions
{
SslRedirect = false,
RequireSsl = false,
LoginCaseSensitive = false,
Users = new[]
{
new BasicAuthAuthorizationUser
{
Login = configuration["ConnectionStrings:Login"], //可视化的登陆账号
PasswordClear = configuration["ConnectionStrings:PasswordClear"] //可视化的密码
}
}
});
return new DashboardOptions
{
Authorization = new[] {
filter
}
};
}
/// <summary>
/// 配置启动
/// </summary>
/// <returns></returns>
public static BackgroundJobServerOptions jobOptions()
{
return new BackgroundJobServerOptions
{
Queues = new[] { "push", "default" },//队列名称,只能为小写
WorkerCount = Environment.ProcessorCount * 5, //并发任务
ServerName = "Hangfire", //代表服务名称
};
}

#endregion

#region 配置服务
public static void HangfireService()
{
//这里呢就是需要触发的方法 "0/10 * * * * ? " 可以自行搜索cron表达式 代表循环的规律很简单

//GameLenthPush代表你要触发的类 UserGameLenthPush代表你要触发的方法

RecurringJob.AddOrUpdate<GameLenthPush>(s => s.UserGameLenthPush(), "0/10 * * * * ? ", TimeZoneInfo.Local);
}
#endregion

}

 

 

在Startup.cs 里面的ConfigureServices方法注入

 HangfireDispose.HangfireServices(services, Configuration);

 

在Startup.cs 里面的Configure方法写入

  app.UseHangfireServer(HangfireDispose.jobOptions());

  app.UseHangfireDashboard("/TaskManager", HangfireDispose.HfDispose(Configuration));

  HangfireDispose.HangfireService();

 

然后新建GameLenthPush类 

   

 public IActionResult UserGameLenthPush()

        {

           return Json(new { code = 0, msg = string.Format("时间{0}", DateTime.Now.ToString()) });

        }

 

 

即可完成Hangfire的部署

启动vs 或者IIS 路径后面添加 /TaskManager  输入你配置的账号密码即可  可视化控制界面

推荐阅读