C# NET4.5 以上 HangFire异步框架使用

文章描述了一个Web应用中使用Hangfire框架进行定时任务调度,包括支付结算、虚拟账户管理、交易记录统计等功能的代码片段。涉及的任务有同步支付分摊账单、批量开户、订单统计等。
摘要由CSDN通过智能技术生成
using Hangfire;
using Microsoft.Owin;
using Owin;
using System;

[assembly: OwinStartup(typeof(SmartPal.Web.Startup))]
namespace SmartPal.Web
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            try
            {
                ConfigureAuth(app);
#if !DEBUG
                app.UseHangfireDashboard("/hangfire", new DashboardOptions
                {
                    DisplayStorageConnectionString = false
                });
                RecurringJob.AddOrUpdate<HangFire.Job>(job => job.SyncPayShareBill(), "0 30 10 * * ? ", TimeZoneInfo.Local);
#endif
                /// <summary>
                /// 批量同步开户(凌晨:02:30:00)
                /// </summary>
                RecurringJob.AddOrUpdate<HangFire.Job>(job => job.SyncCreateVirtual(), "0 30 2 * * ? ", TimeZoneInfo.Local);

                /// <summary>
                /// 间接统计每个商户7天订单交易记录金额总合计(凌晨:01:30:00)
                /// </summary>
                RecurringJob.AddOrUpdate<HangFire.Job>(job => job.SetUserTransRecord(), "0 30 1 * * ? ", TimeZoneInfo.Local);


                /// <summary>
                ///使用老版虚拟户来批量创建丰付前置系统开户及换卡功能 (Hangfire任务)(凌晨:05:01:00)
                /// </summary>
                //RecurringJob.AddOrUpdate<HangFire.Job>(job => job.TaskSyncVirtualAccount(), "0 01 5 * * ? ", TimeZoneInfo.Local);
            }
            catch (Exception ex)
            {
                SmartPalJK.Infrastructure.Context.Logger.Error(String.Format("{0}", ex.Message));
            }
        }
    }
}

using Hangfire;
using SmartPalJK.Core.Models;
using SmartPalJK.Core.Services;
using SmartPalJK.Core.Services.JiuKa;
using SmartPalJK.Core.Services.JiuKa.Model;
using System;

namespace SmartPal.Web.HangFire
{
    public class Job
    {
        public void SyncPayShareBill()
        {
            JiuKaService.SyncEncashPayShareBills(DateTime.Now);
        }
        public void SyncPayShareBillDT(DateTime dt)
        {
            JiuKaService.SyncEncashPayShareBills(dt);
        }

        /// <summary>
        /// 批量同步开户
        /// </summary>
        public void SyncCreateVirtual()
        {
            VirtualService.BusinessVirtualAccount(0,0);
        }

        /// <summary>
        /// 批量同步润物开户状态
        /// </summary>
        public void SyncRuiWuVirtualStatus()
        {
            VirtualService.BusinessVirtualRuiWuAccount(0);
        }


        /// <summary>
        /// 间接统计每个商户7天订单交易记录金额总合计
        /// </summary>
        public void SetUserTransRecord()
        {
            MerchantService.SetUserSevenTransMoney();
        }


        /// <summary>
        /// 使用老版虚拟户来批量创建丰付前置系统开户及换卡功能(Hangfire任务)
        /// </summary>
        public void TaskSyncVirtualAccount()
        {
            VirtualService.TaskSyncVirtualAccount((int)ChanneEnum.FengFuSignSystem);
        }



        /// <summary>
        /// 提交分账任务
        /// </summary>
        /// <param name="encashCollectPayShareId"></param>
        public void ApplyWithdraw(string encashCollectPayShareId)
        {
            var model = EncashCollectPayShareService.Find(encashCollectPayShareId);
            var data = JiuKaService.ApplyWithdraw(model.Id, model.Amount, model.MerId.ToString());
            if (data.Code == Code.Success)//该返回结果表示  提交成功
            {
                model.Status = SmartPalJK.Core.Models.ENCASH_STATUS.ThirdProcessing;
                //加入异步查询任务
                BackgroundJob.Schedule<Job>(job => job.QueryWithDrawStatus(encashCollectPayShareId), TimeSpan.FromMinutes(5));
                EncashCollectPayShareService.UpdateModel(model);
            }
            else//表示提交失败
            {
                model.Status = ENCASH_STATUS.Fail;
                model.Message = data.Message;
                EncashCollectPayShareService.UpdateModel(model);
                PayService.ProccessCollectPayShare(encashCollectPayShareId, (int)ENCASH_STATUS.Fail, 0);
            }
        }

        /// <summary>
        /// 异步更新代付通道金额
        /// </summary>
        public void SyncTransBalanceMoney()
        {
            SettTransBalanceDetailService.BusinessBalanceMoney();
        }


        /// <summary>
        /// GM 润物个人会员提现
        /// </summary>
        public void SyncPayShareRuiWu()
        {
            VirtualExtendBusiness.GMTixianList(DateTime.Now);
        }

        /// <summary>
        /// GM 润物个人会员提现,通过日日期
        /// </summary>
        /// <param name="dt"></param>
        public void SyncPayShareRuiWuByDate(DateTime dt)
        {
            VirtualExtendBusiness.GMTixianList(dt);
        }


        /// <summary>
        /// GM 润物单位会员提现
        /// </summary>
        public void SyncPayShareRuiWuUnitTixian()
        {
            VirtualExtendBusiness.UnitTixianList(DateTime.Now);
        }

        /// <summary>
        /// GM 润物单位会员提现,通过日日期
        /// </summary>
        /// <param name="dt"></param>
        public void SyncPayShareRuiWuUnitTixianByDate(DateTime dt)
        {
            VirtualExtendBusiness.UnitTixianList(dt);
        }

        public void QueryWithDrawStatus(string encashCollectPayShareId)
        {
            //首先判断是否已经经过异步处理 完成了订单状态的更新
            var model = EncashCollectPayShareService.Find(encashCollectPayShareId);
            if (model.Status == ENCASH_STATUS.Succ
                || model.Status == ENCASH_STATUS.SuccPartial
                || model.Status == ENCASH_STATUS.Fail)
            {
                return;
            }
            var data = JiuKaService.QueryWithDrawStatus(encashCollectPayShareId);
            if (data.Code == Code.Success && "100|101|102".Contains(data.Status))
            {
                int status = 0;
                switch (data.Status)
                {
                    case "100":
                        status = (int)ENCASH_STATUS.Succ;
                        break;
                    case "101":
                        status = (int)ENCASH_STATUS.SuccPartial;
                        break;
                    case "102":
                        status = (int)ENCASH_STATUS.Fail;
                        break;
                }
                bool b = PayService.ProccessCollectPayShare(encashCollectPayShareId, status, SmartPalJK.Infrastructure.Utils.Util.GetDecimal(data.SuccessMoney));
            }
            else if (data.Code == Code.Success && "0|1".Contains(data.Status))//申请中  //平台处理中
            {
                //继续加入异步查询任务
                BackgroundJob.Schedule<Job>(job => job.QueryWithDrawStatus(encashCollectPayShareId), TimeSpan.FromMinutes(5));
            }
            else
            {
                //表示查询失败
                //继续加入异步查询任务
                BackgroundJob.Schedule<Job>(job => job.QueryWithDrawStatus(encashCollectPayShareId), TimeSpan.FromMinutes(5));
            }
        }
    }
}
  /// <summary>
        /// 使用老版虚拟户来批量创建丰付前置系统开户及换卡功能
        /// </summary>
        /// <param name="ThoroughfareID"></param>
        /// <returns></returns>
        public static MessageBox TaskSyncVirtualAccount(int? ThoroughfareID)
        {
            if (!ThoroughfareID.HasValue || ThoroughfareID.Value <= 0)
            {
                ThoroughfareID = (int)ChanneEnum.FengFuSignSystem;
            }
            if (!(ThoroughfareID == (int)ChanneEnum.FengFuSignSystem))
            {
                var ErrorMessageStr = " 批量创建丰付前置系统开户及换卡功能--开户通道非法";
                return new MessageBox() { Code = 209, Message = ErrorMessageStr };
            }
            var list = BankAccountService.TaskSyncBankAccountList((int)ChanneEnum.FengFu);
            if (list == null || list.Count <= 0)
            {
                return new MessageBox() { Code = 2001, Message = "" };
            }
            Logger.Error(String.Format("老版本虚拟户数量为:{0}", list.Count));
            var chann = ChannelsServices.Get(ThoroughfareID.Value);
            if (chann == null || String.IsNullOrEmpty(chann.MerId) || String.IsNullOrEmpty(chann.SignKey) || !chann.Status)
            {
                return new MessageBox() { Code = 2003, Message = "" };
            }
            var count = list.Count;
            string StrDomain = ConfigurationManager.AppSettings["JKLocalHOST"];
            string StrNotifyURL = string.Format("{0}/Virtual/NotifySign", StrDomain);
            System.Text.StringBuilder sbError = new StringBuilder();
            String ErrorMessage = "";
            String StrErrChange = "";
            if (count > 0)
            {
                foreach (var itemSigle in list)
                {
                    if (itemSigle == null || itemSigle.MerId <= 0)
                    {
                        continue;
                    }
                    if (
                        String.IsNullOrEmpty(itemSigle.BankName)
                        || !IsNumber(itemSigle.AccountNo)
                        || !IsCn(itemSigle.PayeeName)
                        || !IsCellphoneNum(itemSigle.Phone)
                        || !IsIdentificationCard(itemSigle.IdentityNo)
                        )
                    {
                        Logger.Error(String.Format("批量创建丰付前置系统开户及换卡功能-- 新生成虚拟户条件不符合要求:商户号:{0},银行名称:{1},银行账号:{2},收款人名称:{3},银行账户开户时手机号码:{4},银行账户开户时身份证号:{5}",
                         itemSigle.MerId,
                         itemSigle.BankName,
                         itemSigle.AccountNo,
                         itemSigle.PayeeName,
                         itemSigle.Phone,
                         itemSigle.IdentityNo
                         ));
                        sbError.AppendFormat("ResponseCode={0}", "");
                        sbError.AppendFormat("ResponseMessage={0}", "");
                        sbError.AppendFormat("Content={0}", "批量创建丰付前置系统开户及换卡功能-- 重新生成虚拟户条件不符合要求");
                        ErrorMessage = "重新生成虚拟户条件不符合要求";
                        StrErrChange = "100";
                        continue;
                    }
                    int RepeatMerID = itemSigle.MerId;
                    if (!String.IsNullOrEmpty(itemSigle.RepeatMerID) && itemSigle.RepeatMerID != "0")
                    {
                        RepeatMerID = int.Parse(itemSigle.RepeatMerID);
                    }
                    if (RepeatMerID <= 0)
                    {
                        continue;
                    }
                    bool blCreate = false;
                    bool blChange = false;
                    var searchInfo = SearchVirtualAccount(RepeatMerID, chann.MerId, chann.SignKey, ThoroughfareID.Value);
                    if (
                        searchInfo == null
                        ||
                        searchInfo.SearchVirtualInfo == null
                        ||
                        String.IsNullOrEmpty(searchInfo.SearchVirtualInfo.Status)
                        ||
                        String.IsNullOrEmpty(searchInfo.SearchVirtualInfo.BankAccount)
                        )
                    {
                        blCreate = true;
                    }

                    if (!(itemSigle.IsVirtual == (int)FengFuAccountEnum.Success
                        || itemSigle.IsVirtual == (int)FengFuAccountEnum.PartialSuccess
                        || itemSigle.IsVirtual == (int)FengFuAccountEnum.AgreementUpLoading
                        || itemSigle.IsVirtual == (int)FengFuAccountEnum.RenderParts))
                    {
                        blCreate = true;
                    }
                    if (searchInfo != null
                        &&
                        searchInfo.SearchVirtualInfo != null
                        &&
                        !String.IsNullOrEmpty(searchInfo.SearchVirtualInfo.Mobile)
                        &&
                        !String.IsNullOrEmpty(searchInfo.SearchVirtualInfo.UserName)
                        )
                    {
                        if (
                       searchInfo.SearchVirtualInfo.Mobile != itemSigle.Phone
                       || searchInfo.SearchVirtualInfo.UserName != itemSigle.PayeeName
                       || searchInfo.SearchVirtualInfo.BankAccount != itemSigle.AccountNo
                       || searchInfo.SearchVirtualInfo.BankName != itemSigle.BankName
                       || searchInfo.SearchVirtualInfo.IdentificationCard != itemSigle.IdentityNo
                     )
                        {
                            blChange = true;
                        }
                    }

                    if (blCreate)
                    {
                        var resultChange = CreateVirtualAccountSync(
                            RepeatMerID,
                            chann.MerId,
                            chann.SignKey,
                            itemSigle.PayeeName,
                            itemSigle.AccountNo,
                            itemSigle.BankName,
                            itemSigle.Phone,
                            itemSigle.IdentityNo,
                            StrNotifyURL,
                            ThoroughfareID.Value
                            );
                        if (resultChange == null || String.IsNullOrEmpty(resultChange.ResponseCode))
                        {
                            sbError.AppendFormat("ResponseCode={0}", "");
                            sbError.AppendFormat("ResponseMessage={0}", "");
                            sbError.AppendFormat("Content={0}", "批量创建丰付前置系统开户及换卡功能-- 创建虚拟户时接口地址失败");
                            ErrorMessage = "批量创建丰付前置系统开户及换卡功能-- 创建虚拟户时接口地址失败";
                            StrErrChange = "107";
                            continue;
                        }
                        if (!resultChange.ResponseCode.Equals("10000", StringComparison.OrdinalIgnoreCase))
                        {
                            sbError.AppendFormat("ResponseCode={0}", resultChange.ResponseCode);
                            sbError.AppendFormat("ResponseMessage={0}", resultChange.ResponseMessage);
                            sbError.AppendFormat("Content={0}", "批量创建丰付前置系统开户及换卡功能-- 创建虚拟户时出现错误信息");
                            ErrorMessage = resultChange.ResponseMessage;
                            StrErrChange = "108";
                        }
                    }
                    if (blChange)
                    {
                        var resultChange = ChangeBankVirtualAccountSync(
                                RepeatMerID,
                                chann.MerId,
                                chann.SignKey,
                                itemSigle.PayeeName,
                                itemSigle.AccountNo,
                                itemSigle.BankName,
                                itemSigle.Phone,
                                itemSigle.IdentityNo,
                                StrNotifyURL,
                                ThoroughfareID.Value
                         );
                        if (resultChange == null || String.IsNullOrEmpty(resultChange.ResponseCode))
                        {
                            sbError.AppendFormat("ResponseCode={0}", "");
                            sbError.AppendFormat("ResponseMessage={0}", "");
                            sbError.AppendFormat("Content={0}", "批量创建丰付前置系统开户及换卡功能-- 虚拟户换卡时出现错误信息");
                            ErrorMessage = "批量创建丰付前置系统开户及换卡功能-- 虚拟户换卡时出现错误信息";
                            StrErrChange = "106";
                            continue;
                        }
                        if (!resultChange.ResponseCode.Equals("10000", StringComparison.OrdinalIgnoreCase))
                        {
                            sbError.AppendFormat("ResponseCode={0}", resultChange.ResponseCode);
                            sbError.AppendFormat("ResponseMessage={0}", resultChange.ResponseMessage);
                            sbError.AppendFormat("Content={0}", "批量创建丰付前置系统开户及换卡功能-- 换卡出现错误");
                            ErrorMessage = resultChange.ResponseMessage;
                            StrErrChange = "109";
                        }
                    }
                }
            }
            string sbLogErrContent = sbError.ToString().Trim();
            if (!String.IsNullOrWhiteSpace(sbLogErrContent))
            {
                Logger.Info(String.Format("{0}", sbLogErrContent));
            }
            if (!String.IsNullOrEmpty(ErrorMessage))
            {
                if (StrErrChange.Contains("109"))
                {
                    return new MessageBox() { Code = 205, Message = ErrorMessage };
                }
                if (StrErrChange.Contains("108"))
                {
                    return new MessageBox() { Code = 206, Message = ErrorMessage };
                }
                if (StrErrChange.Contains("106") || StrErrChange.Contains("107"))
                {
                    return new MessageBox() { Code = 207, Message = ErrorMessage };
                }
                if (StrErrChange.Contains("102"))
                {
                    return new MessageBox() { Code = 208, Message = ErrorMessage };
                }
                if (StrErrChange.Contains("100"))
                {
                    return new MessageBox() { Code = 209, Message = ErrorMessage };
                }
            }
            return new MessageBox() { Code = 200, Message = "" };
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值