Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel running job scheduled with Hangfire.io

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.

like image 720
MorioBoncz Avatar asked Feb 10 '15 22:02

MorioBoncz


1 Answers

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.

like image 112
odinserj Avatar answered Sep 21 '22 03:09

odinserj