4

我正在编写一个 MVC 5 互联网应用程序并HangFire用于重复性任务。

如果我有一个每月循环任务,我如何获得下一次执行时间的值?

这是我的重复任务代码:

RecurringJob.AddOrUpdate("AccountMonthlyActionExtendPaymentSubscription", () => accountService.AccountMonthlyActionExtendPaymentSubscription(), Cron.Monthly);

我可以按如下方式检索工作数据:

using (var connection = JobStorage.Current.GetConnection())
{
    var recurringJob = connection.GetJobData("AccountMonthlyActionExtendPaymentSubscription");
}

但是,我不确定下一步该做什么。

是否可以获得重复任务的下一个执行时间?

提前致谢。

4

1 回答 1

16

你很近。我不确定是否有更好或更直接的方法来获取这些详细信息,但 Hangfire 仪表板的方式是使用名为的扩展方法(添加using Hangfire.Storage;到您的导入)GetRecurringJobs()

using (var connection = JobStorage.Current.GetConnection())
{
   var recurring = connection.GetRecurringJobs().FirstOrDefault(p => p.Id == "AccountMonthlyActionExtendPaymentSubscription");

   if (recurring == null)
   {
       // recurring job not found
       Console.WriteLine("Job has not been created yet.");
   }
   else if (!recurring.NextExecution.HasValue)
   {
       // server has not had a chance yet to schedule the job's next execution time, I think.
       Console.WriteLine("Job has not been scheduled yet. Check again later.");
   }
   else
   {
       Console.WriteLine("Job is scheduled to execute at {0}.", recurring.NextExecution);
   }
}

有两个陷阱:

  1. 它返回所有重复的工作,您需要从结果中选择适当的记录
  2. 当您第一次创建作业时,NextExecution时间尚不可用(它将为空)。我相信服务器一旦连接,就会定期检查需要安排的重复任务并这样做;它们似乎不会在使用RecurringJob.AddOrUpdate(...)或其他类似方法创建时立即安排。如果您需要NextExecution在创建后立即获得该值,我不确定您能做什么。不过,它最终会被填充。
于 2015-02-11T07:08:31.747 回答