ASP.NET Core 使用 Hangfire 定时任务
2024-10-10 06:33:13
定时任务组件,除了 Hangfire 外,还有一个 Quarz.NET,不过 Hangfire .NET Core 支持的会更好些。
ASP.NET Core 使用 Hangfire 很简单,首先,Nuget 安装程序包:
> install-package Hangfire -pre
然后ConfigureServices
添加配置代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(x => x.UseSqlServerStorage("<name or connection string>"));
}
上面配置的是 Hangfire 任务配置数据库信息,默认只支持 SQLServer,如果不想使用数据库的话,可以 Nuget 安装程序包:
> install-package Hangfire.MemoryStorage -pre
修改ConfigureServices
配置代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(x => x..UseStorage(new MemoryStorage()));
}
Hangfire 扩展(比如 MySql):https://www.hangfire.io/extensions.html
然后Configure
添加配置代码:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseHangfireServer();
app.UseHangfireDashboard();
RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring!"), Cron.Minutely());
}
上面配置代码一分钟执行一次,Hangfire 支持 UI 界面展示,地址:http://localhost:8089/hangfire
Hangfire 默认也支持执行异步方法,RecurringJob
方法签名:
public static void AddOrUpdate<T>(Expression<Func<T, Task>> methodCall, string cronExpression, TimeZoneInfo timeZone = null, string queue = "default");
public static void AddOrUpdate(Expression<Func<Task>> methodCall, string cronExpression, TimeZoneInfo timeZone = null, string queue = "default");
public static void AddOrUpdate<T>(Expression<Func<T, Task>> methodCall, Func<string> cronExpression, TimeZoneInfo timeZone = null, string queue = "default");
public static void AddOrUpdate(Expression<Func<Task>> methodCall, Func<string> cronExpression, TimeZoneInfo timeZone = null, string queue = "default");
异步和同步使用没有任何区别,示例代码:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseHangfireServer();
app.UseHangfireDashboard();
RecurringJob.AddOrUpdate(() => TestAsync(), Cron.Minutely());
}
public static async Task TestAsync()
{
// to do...
}
参考资料:
- Hangfire
- ASP.NET Core 开发-后台任务利器 Hangfire 使用
- Hangfire Async Methods for Background Jobs
- How to invoke async methods in Hangfire?
最新文章
- Entity Framework 6 Recipes 2nd Edition(12-3)译 ->; 数据库连接日志
- Zend Studio 11.0 汉化
- .net MVC3 页面和 action 传值问题
- PSP个人项目耗时记录
- android 音频焦点
- mysql避免重复插入的三种方法
- Eclipse和MyEclipse工程描述符.classpath和.project和.mymetadata详解aaaaaa(转)
- HTTP协议学习---(三)摘要认证
- jQuery插件-表单验证插件-Validation
- photoshop菜单显示不全的解决方法
- tl;drLegal ——开源软件license的搜索引擎
- IOS下双击背景, touchmove, 阻止页面背景scroll.
- MMC卡是什么
- Windows Service的官方描述,抄下来(不写obj就是LocalSystem)
- 网络资源(5) - Android视频
- Qt5中this application has requested the runtime to terminate it in an unusual way 无法运行问题的解决
- 并发的HashMap为什么会引起死循环?
- Vagrant 创建虚拟环境
- BZOJ5343[Ctsc2018]混合果汁——主席树+二分答案
- HTML 中使 footer 始终处于页面底部