Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

c# - HangFire recurring task data

I am coding a MVC 5 internet application and am using HangFire for recurring tasks.

If I have a Monthly recurring task, how can I get the value of the next execution time?

Here is my code for the recurring task:

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

I can retrieve the job data as follows:

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

However, I am not sure as to what to do next.

Is it possible to get the next execution time of a recurring task?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're close. I'm not sure if there is a better or otherwise more direct way to get these details, but the way the Hangfire Dashboard does it is to use an extension method (add using Hangfire.Storage; to your imports) called 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);
   }
}

There are two catches:

  1. It returns all recurring jobs, and you'll need select the appropriate record out of the result
  2. When you first create the job, the NextExecution time is not available yet (it will be null). I believe the server, once one connects, periodically checks for recurring tasks that need to be scheduled and does so; they do not appear to be immediately scheduled upon creation using RecurringJob.AddOrUpdate(...) or other such similar methods. If you need to get that NextExecution value immediately after creation, I'm not sure what you can do. It will eventually be populated, though.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...