How to pass hangfire jobId to method call in RecurringJob.AddOrUpdate?

Hello,

I am using RecurringJob.AddOrUpdate Method (String, Expression, String, TimeZoneInfo, String) to set up recurring tasks.

I wish to access the JobId of the triggered recurring job inside the Action for logging purpose. I read other questions about JobId in jobs here but in the case of recurring jobs it seems a bit different because I don’t have a handle on BackgroundJob.

All the hangfire logic is isolated and unknown from the rest of the business logic entered with the Action, therefore I wish to pass the jobId as parameter of Action) and it is executed at deployment (were jobIds are not created yet)

you can use the PerformContext for this. This context will be set by hangfire when it executes the action.

public void MyMethod(PerformContext context)
{
   string jobId = context.BackgroundJob.Id;
}

When using RecurringJob.AddOrUpdate set the parameter to null

RecurringJob.AddOrUpdate("name", () => MyMethod(null), "* * * * *");
1 Like

Like IJobCancellationToken , PerformContext is a special argument type that Hangfire will substitute automatically. You should pass null when enqueuing a job.