ASP.NET Core 使用 Hangfire 定时任务

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

435188-20170425202305678-916877046.png

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...
}

参考资料:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值