Search code examples
c#hangfire

Hangfire - get next execution time


I have a reccuring job in Hangfire which is triggered by CronTemplate. I need to get next execution time during the job execution.

I came up with an idea to inject CronTemplate into the job and calculate that date using some of existing libraries based on the template, but I have some design concerns about this solution and I think a solution based on some kind of JobExecutionContext would be better, but so far I couldn't find any way to get it.

Does something similar exist in Hangfire? If so, how can I access it?

Any idea would be appreciated.


Solution

  • Alex here is some pseudo code that might just answer your question.

    private DateTime? GetNextExecutionTime(MethodInfo methodInfo)
    {
        try
        {
            var job = JobStorage.Current.GetConnection().GetRecurringJobs().Single(x => x.Job.Method == methodInfo);
            return job == null ? null : job.NextExecution;
        }
        catch (Exception)
        {
            return null;
        }
    }