Cancel running job scheduled with Hangfire.io
Asked Answered
K

2

7

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.

Krugersdorp answered 10/2, 2015 at 22:59 Comment(2)
Hi did you ever find out how to cancel/delete a queued or running task>?Dogmatic
To programmatically cancel a job, call BackgroundJob.Delete. See: discuss.hangfire.io/t/cancel-a-running-job/603Arte
R
5

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.

Retrorse answered 11/2, 2015 at 10:47 Comment(1)
Ok, thanks. I was checking the flag on ShutdownToken instead of using ThrowIfCancellationRequested which internally pulls database.Krugersdorp
M
0

This works if you delete the job from the dashboard

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.");
}
Module answered 30/3, 2017 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.