HangFire get last and next execution datetime

Smith
Smith
None
2568 Points
74 Posts

I am using  hangfire to schedule job.  Is there any  method get last/previous and next execution date time?

Views: 15967
Total Answered: 2
Total Marked As Answer: 1
Posted On: 21-Apr-2017 05:00

Share:   fb twitter linkedin
Answers
sam
sam
Member
378 Points
48 Posts
         

Get next job execution date-time:

RecurringJob.AddOrUpdate("SomeJobId", () => accountService.someJob(), Cron.Monthly);
using Hangfire.Storage;
using Hangfire;

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

   if (recurringJob == null)
   {
       // recurring job not found
       Console.WriteLine("Job has not been created yet.");
   }
   else if (!recurringJob.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}.", recurringJob.NextExecution);
   }
}
Posted On: 26-Apr-2017 03:55
Rahul Maurya
Rahul M...
Teacher
4822 Points
23 Posts
         

Suppose you have scheduled job in hang-fire by adding jobId='myjobid' which is scheduled for monthly execution as:

RecurringJob.AddOrUpdate<MyService>("myjobid", ms => ms.MyJobMonthly(), "0 0 1 * *");

Then you and get last execution date-time and next execution date-time as:

using Hangfire.Storage;
using Hangfire;

DateTime LastExecutionDateTime = DateTime.Now;
DateTime NextExecutionDateTime = DateTime.Now;
using (var connection = JobStorage.Current.GetConnection())
{
   var job = connection.GetRecurringJobs().FirstOrDefault(p => p.Id == "myjobid");
   if (job != null && job.LastExecution.HasValue)
      LastExecutionDateTime = job.LastExecution ?? DateTime.Now;
   if (job != null && job.NextExecution.HasValue)
      NextExecutionDateTime = job.NextExecution ?? DateTime.Now;
}
Console.WriteLine("Job last/next execution time: {0}/{1}.", LastExecutionDateTime, NextExecutionDateTime);
Posted On: 26-Apr-2017 04:07
 Log In to Chat