Cancel or Delete Scheduled Job - HangFire
Asked Answered
Y

2

18

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.

Yippie answered 8/8, 2018 at 21:42 Comment(0)
R
31

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);
Rosin answered 9/8, 2018 at 12:6 Comment(1)
For this I need to save the JobId in database so I can use that later when needed.Yippie
S
10

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

Skyward answered 10/10, 2020 at 17:30 Comment(1)
I'm trying to do something similar to this, however, if its automated, you will not know what the ID is in the "DeleteExistingJobs" is, unless you look in the Hangfire UI.Partee

© 2022 - 2024 — McMap. All rights reserved.