Search code examples
c#asp.net-corebackgroundworkerhangfire

How to stop and delete all processing background jobs in hangfire?


I'm using Hangfire in AspNet Core project to run some background jobs. When I restart my server, new backround job enqueued and processing, but all previous background jobs continuous processing or restarting. I have removed all old processing background jobs from database, but nothing changed, this deleted job was removed from database but still processing. How can I stop and delete all processing background jobs, which are not reflect in the database?


Solution

  • First, you should use cancellation tokens. In you job, pass an IJobCancellationToken object as argument along your other arguments:

    public void MyJob( <<other args>>, IJobCancellationToken cancellationToken)
    {
        for (var i = 0; i < Int32.MaxValue; i++)
        {
            cancellationToken.ThrowIfCancellationRequested();
    
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
    }
    

    To enqueue your job pass IJobCancellationToken as null:

    string jobID = BackgroundJob.Enqueue(() => MyJob(<<other args>>, JobCancellationToken.Null));
    

    Now to cancel and remove a job, do it through code:

    BackgroundJob.Delete(jobID);