Cancel job launch using Hangfire.io

I plan to work using the hangfire.io library, and I can observe its processing in the built-in panel. However, my system has a requirement that the task can be canceled from the toolbar.

It is possible to delete the current task, but this only changes the state of the task in the database and does not stop working.

I see that the documentation has the option to pass the IJobCancellationToken , however, as I understand it, it is used to stop the job correctly when the entire server is disconnected.

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

Do I have to write my own component that periodically displays the database and checks if the current instance of the server is running a job that has been canceled? For example, maintain the dictionary jobId -> CancellationTokenSource, and then cancel the signal cancellation using the appropriate token.

+5
source share
2 answers

The documentation is incomplete. IJobCancellationToken.ThrowIfCancellationRequested method throws an exception after any of the following conditions is IJobCancellationToken.ThrowIfCancellationRequested :

  • Shutting down the Hangfire server. This event fires when someone calls the Stop or Dispose BackgroundJobServer methods.
  • The background job is not in the Processed state.
  • The background job is being performed by another employee.

The last two cases are performed by querying the job store for the current state of the background job. Thus, the cancel marker will be thrown if you remove or reinstall it from the control panel.

+3
source

This works if you delete a task from the control panel.

 static public void DoWork(IJobCancellationToken cancellationToken) { Debug.WriteLine("Starting Work..."); for (int i = 0; i < 10; i++) { Debug.WriteLine("Ping"); try { cancellationToken.ThrowIfCancellationRequested(); } catch (Exception ex) { Debug.WriteLine("ThrowIfCancellationRequested"); break; } //Debug.WriteProgressBar(i); Thread.Sleep(5000); } Debug.WriteLine("Finished."); } 
0
source

Source: https://habr.com/ru/post/1213094/


All Articles