hangfire在.netCore中调用

HangFire在.netCore中如何使用不在介绍了,不会的可以搜索一下,有很多

但是写完如何调用呢?

1、定时任务,创建 RecurringJobService类,

    //定时任务
    public class RecurringJobService : IRecurringJobService
    {
         public async void DoJob()
        {
             //在这里编写需执行的业务逻辑      
        }
     }

1.1 创建 HangfireServiceExtension.cs  类,调用定时任务需要执行的方法

Cron表达式还有另一种写法 0 0/2 * ** ?  表示每2分钟,有兴趣可自行查询

using Hangfire;
public
static class HangfireServiceExtension { internal static void HangfireService(this IApplicationBuilder app) { try {

                 //在这里进行方法调用,x=>x.DoJob() 
                 RecurringJob.AddOrUpdate<IRecurringJobService>("Job", x => x.DoJob(), Cron.Daily(1, 10), TimeZoneInfo.Local, "default");

            }
            catch (Exception)
            {
                throw;
            }
        }
    }

1.2 项目启动时加载定时任务,在启动项 Startup.cs 中 Configure 下调用HangfireService

app.HangfireService();

以上就是定时任务完整的调用过程,同理如果是延时任务,比如下单10分钟没有进行支付,订单自动取消,

创建订单后启动延迟任务

2.延迟任务,创建 BackgroundJobService 类

    /// <summary>
    /// Handfire延迟任务
    /// </summary>
    public class BackgroundJobService : IBackgroundJobService
    {

        /// <summary>
        /// 待支付订单 10分钟后自动取消
        /// </summary>
        /// <param name="DelayedjobId">返回任务key</param>        public string AddOrderExpiredJob(long orderid)

        {
            TimeSpan ts = TimeSpan.FromHours(24);
var DelayedjobId = BackgroundJob.Schedule<_order_ListService>(x => x.OrderExpired(orderid), ts);
//delayedjobid 为创建延迟任务成功后,返回的任务id,持久化到数据库中,
//如订单支付成功,可通过任务id,删除延迟任务
if (!string.IsNullOrEmpty(DelayedjobId)) { _relationService.Add(new JobRelation() { CreateAt = DateTime.Now, JobId = DelayedjobId, KeyId = KeyId, Type = HangfireJobType.OrderCancel //枚举,代表订单取消 }); } return DelayedjobId; } }
_order_ListService为订单接口,OrderExpired为接口下取消订单的具体方法,ts为多少分钟后指定取消订单的方法

 

posted @ 2022-09-16 16:48  吃辣椒的小毛驴  阅读(478)  评论(0编辑  收藏  举报