定时任务组件,除了 Hangfire 外,还有一个 Quarz.NET,不过 Hangfire .NET Core 支持的会更好些。
ASP.NET Core 使用 Hangfire 很简单,首先,Nuget 安装程序包:
> install-package Hangfire -pre
public void ConfigureServices(IServiceCollection services) { services.AddHangfire(x => x.UsesqlServerStorage("<name or connection string>")); }
上面配置的是 Hangfire 任务配置数据库信息,默认只支持 sqlServer,如果不想使用数据库的话,可以 Nuget 安装程序包:
> install-package Hangfire.MemoryStorage -pre
public void ConfigureServices(IServiceCollection services) { services.AddHangfire(x => x..UseStorage(new MemoryStorage())); }
Hangfire 扩展(比如 MysqL):https://www.hangfire.io/extensions.html
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... }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。