16

I have scheduled a Job via using Hangfire library. My scheduled Code like below.

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

public static bool DownGradeUserPlan(int userId)
    {
        //Write logic here
    }

Now I want to Delete this Scheduled Job later on some event.

Vijjendra
  • 24,223
  • 12
  • 60
  • 92

2 Answers2

28

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);
Vijjendra
  • 24,223
  • 12
  • 60
  • 92
Alex Riabov
  • 8,655
  • 5
  • 47
  • 48
9

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

Karr
  • 395
  • 5
  • 9