If I’m understanding your question correctly, I think the Hangfire dashboard does allow stopping a job that is processing (or, more correctly, “requesting” that a job be stopped).
If you have a job that takes some time and is currently processing/running, in the Hangfire dashboard page, select the “Jobs” item in the top navigation bar. This shows entries for Enqueued, Scheduled, Processing, etc. Click the “Processing” entry, and you should see your currently processing job (or jobs). Check the checkbox at the beginning of the line showing the job that you want to stop, and then click the “Delete selected” button at the top. You will be prompted, asking whether you want to delete the job - click OK.
This will stop/cancel the executing job in Hangfire’s queue and move it from the “Processing” list to the “Deleted” list in the “Jobs” page. Note that if this was a recurring job, it will still be in the list of recurring jobs - the “delete” operation here only deletes (cancels) the single instance of the job from currently processing; it does not delete the job from the recurring list.
However, this does NOT actually stop the code that is running within the job. For that, you will need to use a cancellation token, and your code needs to be such that you have intermediate places where you can periodically check the state of the cancellation token.
This is briefly explained at: Using cancellation tokens — Hangfire Documentation and the following is my very cursory understanding of one way to use this process.
First, you need to add a CancellationToken parameter to your method that you are scheduling, such as:
public static string LongRunningJob(CancellationToken token)
Second, when you enqueue this job (either singly or recurring), pass a Null cancellation token to it, such as:
“=> LongRunningJob(CancellationToken.None)”
Hangfire will automatically replace this Null token with its own unique token for each instance of a job.
Third, at intervals within your code for the called method, you need to check the state of the cancellation token. For example, if you are performing database operations, you can check after each record update; if you are sending a batch of emails, you can check after each email, etc. Check if the job has been canceled with code like this:
if (token.IsCancellationRequested)
{
// Perform any cleanup required, or log the cancellation
// Perhaps, keep track of the last item processed or similar
return "CANCELED"; // Or similar
}
Note: You can also (more simply) just cause/raise an exception in your long-running code if it has been cancelled - by periodically calling “token.ThrowIfCancellationRequested();”