Get the (ID of the) parent job by the (ID of the) current job

Hello everyone,

is there a way to get the parent job by the ID of the current job? E.g. I have the job with the ID 123. Now I would like to increase the expiretime of the parent job to a few days/weeks. Is there a way to get the parent job (commonly with the ID 122 in this case) and the object of this job in Visual Basic/C#?

Thanks and regards,
Marvin Klar

So you have at least two questions:

  1. Is there a way to get the parent job by the ID of the current job?
  2. How to increase expiration time of a job?

So first question first:
Unfortunately not. But when you create the child job, you could provide the parent job id as argument. With a given parental job id as argument it is easy to access everything of this (or any other) job through the PerformContext.

Here is an example:

public class SomeWorker
{
    private readonly IBackgroundJobClient _jobClient;

    public SomeWorker(IBackgroundJobClient jobClient)
    {
        _jobClient = jobClient;
    }

    public void EnqueueTasks()
    {
        // Enqueue a job and retrieve the id of this job:
        var jobId = _jobClient.Enqueue(() => DoSomething());

        // Add a continuation to this job and provide the parent job id:
        _jobClient.ContinueJobWith(jobId, () => ChildDoSomething(jobId, null), JobContinuationOptions.OnAnyFinishedState);
    }

    public void DoSomething()
    {
        Console.WriteLine("Just did it");
    }

    public void ChildDoSomething(string parentalJobId, PerformContext context)
    {
        // Get job information from the given parental job id:
        var data = context.Connection.GetJobData(parentalJobId);
        var state = data.State;

        Console.WriteLine($"My parental job is in state {state}");

        // For checking against any well-known state, take its corresponding name:
        if (state == SucceededState.StateName)
        {
            Console.WriteLine("Hooray, my parental job succeeded");
        }
    }
}

The second one isn’t possible through the PerformContext AFAIK. For other approaches take a look at this topic: How to configure the retention time of job? - #2 by odinserj
But I don’t think you can do it via the provided classes or interfaces on a per job level. For this you have to write some low-level code against your used storage provider. In case of SQL you could directly access the table HangFire.Job and set the ExpireAt column of the given Id row to your desired value and for the other storage provider inspect their raw data, find the data and manipulate it directly.