How to cancel current execution of Recurring Job?

Hi, I’m trying to find a way to cancel the current execution of a recurring job.

I’ve already tested BackgroundJob.Delete() and this correctly throws a JobAbortedException within a job that is currently executing as long as it invokes ThrowIfCancellationRequested() on its cancellation token.

However, calling RecurringJob.RemoveIfExists() only deletes the recurring job definition, and doesn’t cancel any running background jobs that were created from the recurring job definition.

Basically I need a way to be able to lookup any background jobs that are associated with a recurring job, and manually cancel them using the Delete() method. However, I don’t know how to do this or if it is even possible.

Can anyone provide any help please?

I just found the solution, which I’ll include here for posterity:

List<RecurringJobDto> list;
using (var connection = JobStorage.Current.GetConnection())
{
    list = connection.GetRecurringJobs();
}

var job = list?.FirstOrDefault(j => j.Id == jobId);  // jobId is the recurring job ID, whatever that is
if (job != null && !string.IsNullOrEmpty(job.LastJobId))
{
    BackgroundJob.Delete(job.LastJobId);
}

Can you help me on how to delete All Current Execution(s) of a specific recurring job … not just the latest ?

Thank you,
Fady Naguib

I have Create one Recuring job

RecurringJob.AddOrUpdate("abc", () => Process(), Cron.MinuteInterval(1));
is working good but this job not stop on this code

List<RecurringJobDto> list;
            using (var connection = JobStorage.Current.GetConnection())
            {
                list = connection.GetRecurringJobs();
            }
            var job = list?.FirstOrDefault(j => j.Id == "abc");  // jobId is the recurring job ID, whatever that is
            if (job != null && !string.IsNullOrEmpty(job.LastJobId))
            {
                BackgroundJob.Delete(job.LastJobId);
                RecurringJob.RemoveIfExists(job.LastJobId);
            }

Please help me how to stop or remove this job

I have to agree with @ParinPatel
Running this code will not actually stop the execution of the Scheduled job.
It will remove it from the Hangfire Dashboard - Processing and move it to Deleted

BUT… the job will actually continue running in the background. at least for me.
it might have something to do with my personal solution though, but i dont think so.
does anyone have any insight into this?

Have you tried periodically checking if the job is “Deleted”?

                            IStorageConnection connection = JobStorage.Current.GetConnection();
                            JobData jobData = connection.GetJobData(jobId.Value.ToString());

                            if (jobData.State == "Deleted")
                            {
                             // stop processing
                            }