Master_T
Master_T

Reputation: 7913

How to detect when a job was canceled in Quartz.net?

I'm using Quartz.net 3.x, and following what little documentation I could find on the subject, I've implemented the ability for my job to be canceled, like this:

public class MyJob : IJob
  public async Task Execute(IJobExecutionContext context)
  {
      //Do some stuff...
      context.CancellationToken.ThrowIfCancellationRequested();
      //Do other stuff...
  }
}

This seems to work correctly, in fact when if cancel the job, by calling the following code

scheduler.Interrupt(myJobKey);

the job stops when it hits the next ThrowIfCancellationRequested() instruction.

However, the problem is that I have a IJobListener that, when a job finishes, needs to check if the job was cancelled or if it finished correctly. I've tried to implement it like this:

public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default(CancellationToken))
            {
    if(jobException != null && jobException.InnerException is OperationCanceledException){
        //doesn't work, when a OperationCanceledException was raised as a result of calling ThrowIfCancellationRequested() jobException is null 
    }

    if(cancellationToken.IsCancellationRequested){
        //doesn't work either, IsCancellationRequested is always false
    }
}

What am I missing here? I currently have a workaround where I set the job context's Result property to a custom value that tells me that the job was cancelled, but surely there's a "proper" way to do this?

Upvotes: 1

Views: 1392

Answers (1)

Master_T
Master_T

Reputation: 7913

I found out the problem: apparently I should be the one to manually throw JobExecutionException inside the job's Execute method, Quartz doesn't automatically do it when the method throws any other exceptions. Or, at least, it doesn't ALWAYS automatically do it, because it was doing it when I re-threw other exception types... maybe it automatically handles only some types of exceptions?

I don't know, but this works:

public class MyJob : IJob
  public async Task Execute(IJobExecutionContext context)
  {
      //Do some stuff...
      try{
        context.CancellationToken.ThrowIfCancellationRequested();
      } 
      catch(OperationCanceledException ex){
        throw new JobExecutionException(ex);
      }
      //Do other stuff...
  }
}

Upvotes: 1

Related Questions