ABP之使用Hangfire

首先ABP自带Hangfire,所以我们今天使用Volo.Abp.BackgroundJobs.HangFire

1、在项目需要位置引入Nuget包(6.0.3)

image

2、再引入基于内容的存储库:Hangfire.MemoryStorage(1.7.0)

image

3、Hangfire.MemoryStorage不是abp封装的,所以可能会存在里面引用的Hangfire.Core 版本和Volo.Abp.BackgroundJobs.HangFire不一致的问题。只需要再引用Hangfire.Core,二者最高的版本即可。(1.7.29)

image

4、引入完之后,在项目的HttpApiHostModule.cs 文件中进行配置

image
引入依赖模块typeof(AbpBackgroundJobsHangfireModule)
image

5、ConfigureServices(ServiceConfigurationContext context)方法中进行配置

点击查看代码
context.Services.AddHangfire(config => {
    // config.UseStorage(new MySqlStorage("server=127.0.0.1;database=patent;uid=root;pwd=WWW.1633.com;charset=utf8mb4;Allow User Variables=true;"));
    config.UseMemoryStorage();
});

6、OnApplicationInitialization(ApplicationInitializationContext context)初始方法

点击查看代码
app.UseHangfireDashboard("/hangfire"); //启用hangfire面板
app.UseHangfireServer();

image

7、定义工作类

image

记得要注入依赖,这边注入一个ITransientDependency类型
image
我这边是自己定义了DBhelpder和Redis帮助类、也可以不定义、看个人写法吧

当然有个简单的小实现

点击查看代码
public class JobForDaiLiShiCase :  ITransientDependency
    {
        public ITongJiDaiLiShiCaseService _tongJiDaiLiShiCaseService { get; set; }

      
        public async Task Run()
        {
            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
           // await _tongJiDaiLiShiCaseService.TongJiAsync();
        }
    }

然后,我们同样在 项目的 .module.cs文件中去调用任务

点击查看代码
app.UseHangfireDashboard("/hangfire"); //启用hangfire面板
            app.UseHangfireServer();
           

           
            // 创建每1分钟调用一次的定时任务
            RecurringJob.AddOrUpdate<JobForDaiLiShiCase>(x => x.Run(), "0/2 * * * * ?");
posted @ 2024-07-04 16:17  北落师门、  阅读(12)  评论(0编辑  收藏  举报