zoukankan      html  css  js  c++  java
  • 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

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

    参考资料:

  • 相关阅读:
    Qt double转换成Qstring
    QT 控件ComboBox
    前端web项目打包(二)
    前端Web打包成可执行程序
    div中下拉框无法点击展开跟选中
    div下多个table并排排列
    VS将数据保存在excel表格中
    关于windows下任务栏应用程序标签消失问题的解决办法
    Java8中map()和flatMap()的区别
    Java对象的深拷贝
  • 原文地址:https://www.cnblogs.com/xishuai/p/asp-net-core-hangfire.html
Copyright © 2011-2022 走看看