Cancel running job scheduled with Hangfire.io

MorioBoncz picture MorioBoncz · Feb 10, 2015 · Viewed 8.1k times · Source

I schedule job using hangfire.io library and I can observe it being processed in built in dashboard. However, my system has requirement that the job can be cancelled from the dashboard.

There is an option to delete running job, but this only changes the state of the job in database and does not stop running job.

I see in documentation there is option to pass IJobCancellationToken however as I understand it it is used to correctly stop the job when whole server is shutting down.

Is there a way to achieve programmatic cancellation of already running task?

Should I write my own component that would periodically pull database and check whether current server instance is running job that has been cancelled? For instance maintain dictionary jobId -> CancellationTokenSource and then signal cancellation using appropriate tokensource.

Answer

odinserj picture odinserj · Feb 11, 2015

Documentation is incomplete a bit. IJobCancellationToken.ThrowIfCancellationRequested method throws an exception after any of the following conditions met:

  1. Hangfire Server shutdown initiated. This event is triggered when someone calls Stop or Dispose methods of BackgroundJobServer.
  2. Background job is not in Processed state.
  3. Background job is being performed by another worker.

The latter two cases are performed by querying job storage for the current background job state. So, cancellation token will throw if you delete or re-queue it from the dashboard also.