Cancel or Delete Scheduled Job - HangFire

You don't need to save their IDs to retrieve the jobs later. Instead, you can utilize the MonitoringApi class of the Hangfire API. Note that, you will need to filter out the jobs according to your needs.

Text is my custom class in my example code.

public void ProcessInBackground(Text text)
{
    // Some code
}

public void SomeMethod(Text text)
{
    // Some code

    // Delete existing jobs before adding a new one
    DeleteExistingJobs(text.TextId);

    BackgroundJob.Enqueue(() => ProcessInBackground(text));
}

private void DeleteExistingJobs(int textId)
{
    var monitor = JobStorage.Current.GetMonitoringApi();

    var jobsProcessing = monitor.ProcessingJobs(0, int.MaxValue)
        .Where(x => x.Value.Job.Method.Name == "ProcessInBackground");
    foreach (var j in jobsProcessing)
    {
        var t = (Text)j.Value.Job.Args[0];
        if (t.TextId == textId)
        {
            BackgroundJob.Delete(j.Key);
        }
    }

    var jobsScheduled = monitor.ScheduledJobs(0, int.MaxValue)
        .Where(x => x.Value.Job.Method.Name == "ProcessInBackground");
    foreach (var j in jobsScheduled)
    {
        var t = (Text)j.Value.Job.Args[0];
        if (t.TextId == textId)
        {
            BackgroundJob.Delete(j.Key);
        }
    }
}

My reference: https://discuss.hangfire.io/t/cancel-a-running-job/603/10


BackgroundJob.Schedule returns you an id of that job, you can use it to delete this job:

var jobId = BackgroundJob.Schedule(() =>  MyRepository.SomeMethod(2),TimeSpan.FromDays(7));

BackgroundJob.Delete(jobId);