定时任务组件,除了 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...
}

参考资料:

最新文章

  1. Entity Framework 6 Recipes 2nd Edition(12-3)译 -&gt; 数据库连接日志
  2. Zend Studio 11.0 汉化
  3. .net MVC3 页面和 action 传值问题
  4. PSP个人项目耗时记录
  5. android 音频焦点
  6. mysql避免重复插入的三种方法
  7. Eclipse和MyEclipse工程描述符.classpath和.project和.mymetadata详解aaaaaa(转)
  8. HTTP协议学习---(三)摘要认证
  9. jQuery插件-表单验证插件-Validation
  10. photoshop菜单显示不全的解决方法
  11. tl;drLegal ——开源软件license的搜索引擎
  12. IOS下双击背景, touchmove, 阻止页面背景scroll.
  13. MMC卡是什么
  14. Windows Service的官方描述,抄下来(不写obj就是LocalSystem)
  15. 网络资源(5) - Android视频
  16. Qt5中this application has requested the runtime to terminate it in an unusual way 无法运行问题的解决
  17. 并发的HashMap为什么会引起死循环?
  18. Vagrant 创建虚拟环境
  19. BZOJ5343[Ctsc2018]混合果汁——主席树+二分答案
  20. HTML 中使 footer 始终处于页面底部

热门文章

  1. winscp连接虚拟机Linux被拒绝的问题解决方案
  2. whonix官网部分翻译
  3. 免费好用的阿里云云盾证书服务(https证书)申请步骤
  4. 清理win10过期补丁的命令
  5. 非对称加密技术- RSA算法数学原理分析
  6. C#实现的apache htpasswd加密
  7. Cordic算法——圆周系统之旋转模式
  8. FPGA时钟分频(转)
  9. c语言的预处理指令分3种   1&gt; 宏定义   2&gt; 条件编译   3&gt; 文件包含
  10. 数据库—Mysql