You can achieve this by using IMonitorinApi and fetch jobs that are processing. Then you can delete them by using IBackgroundJobClient. You need to pass in a cancellationtoken though.
public void InitializeJobs()
{
const string myRecurringJobId = "Ftmch-20";
_recurringJobManager.AddOrUpdate(
myRecurringJobId,
Job.FromExpression<MyJob>(j => j.LongRunningJob(null, CancellationToken.None)),
"0/10 * * * * *");
}
…
public class MyJob
{
private readonly IBackgroundJobClient _backgroundJobClient;
public MyJob(IBackgroundJobClient backgroundJobClient) => _backgroundJobClient = backgroundJobClient;
public void LongRunningJob(PerformContext context, CancellationToken cancellationToken)
{
var currentJobId = context.BackgroundJob.Id;
var monitoringApi = JobStorage.Current.GetMonitoringApi();
var jobsToDelete = monitoringApi.ProcessingJobs(0, 1000)
.Where(j => j.Value.Job.Type == typeof(MyJob))
.Where(j => j.Key != currentJobId)
.ToList();
foreach (var jobToDelete in jobsToDelete)
{
_backgroundJobClient.Delete(jobToDelete.Key);
}
var endTime = DateTime.UtcNow.AddMinutes(5);
while (endTime > DateTime.UtcNow)
{
cancellationToken.ThrowIfCancellationRequested();
Thread.Sleep(2000);
}
}
}