【问题标题】:Set a job to failed using Hangfire with ASP.NET?使用带有 ASP.NET 的 Hangfire 将作业设置为失败?
【发布时间】:2016-04-07 19:45:35
【问题描述】:

我有一个 ASP.NET 应用程序,只要用户在网站上注册,它就会发送电子邮件。我正在使用 hangfire 来管理工作和邮政以发送电子邮件。

一切都很好,但事情是这样的:

我希望超级用户在删除作业之前更改 APP 可以发送电子邮件的次数。

这是我的代码

    public static void WelcomeUser(DBContexts.Notifications not)
    {
        try{
            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            Postal.EmailService service = new Postal.EmailService(engines);

            WelcomeUserMail welcomeUserMail = new WelcomeUserMail();
            welcomeUserMail.To = not.ReceiverEmail;
            welcomeUserMail.UserEmail = not.ReceiverEmail;
            welcomeUserMail.From = BaseNotification.GetEmailFrom();

            service.Send(welcomeUserMail);
        }
        catch(Exception e)
        {
            DBContexts.DBModel dbModel = new DBModel();
            DBContexts.Notifications notificacionBD =  dbModel.Notifications.Find(not.NotificationID);

            notificacionBD.Status = false;
            notificacionBD.Timestamp = DateTime.Now;
            notificacionBD.Error = e.Message;

            int numberOfRetriesAllowed = ParameterHelper.getNumberOfRetriesAllowed();

            if (notificacionBD.Retries > numberOfRetriesAllowed)
            {
                //In this case Hangfire won't put this job in the failed section but rather in the processed section.
                dbModel.SaveChanges();
            }
            else
            {
                notificacionBD.Retries++;
                dbModel.SaveChanges();

                throw new Exception(e.Message);
            }
        }
    }

【问题讨论】:

    标签: asp.net jobs hangfire postal


    【解决方案1】:

    为什么不直接添加属性来自动处理呢?

    [AutomaticRetry(Attempts = 10, LogEvents = true, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
    public void MyTask(){
        //doing stuff
    }
    

    或者您可以创建自己的属性来模仿 AutommaticRetryAttribute 类,但您可以按照自己的意愿处理它?

    https://github.com/HangfireIO/Hangfire/blob/a5761072f18ff4caa80910cda4652970cf52e693/src/Hangfire.Core/AutomaticRetryAttribute.cs

    【讨论】:

    • 嗯,重点是我希望允许超级用户更改尝试次数。这就是为什么我想以我的方式处理它。
    • 对。您可以通过查看 AutomaticRetryAttribute 的完成方式来创建自己的 AutomaticRetry 属性,但用您自己的条件替换,也许?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-05-20
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多