Hangfire run background job only once
Asked Answered
D

2

5

I have one hangfire server running. I created a background job as follows

  BackgroundJob.Enqueue(() => new MyJob().Execute(path));

This job should run just once but in the processing jobs part of the web portal i see it running multiple times at once. How do I prevent this and ensure that the job is only ever kicked off once?

Dashboard answered 15/9, 2015 at 10:50 Comment(3)
Have you put a breakpoint on the BackgroundJob.Enqueue to see if it's getting called multiple times? Where is that line of code?Oz
that is correct syntax to make a fire and forget call. that should run once. what does Execute method do?Mease
I am running this in an Azure website. The code runs only once on startup. Perhaps it is adding another job if the app pool recycles which seems to happen often. Is there a way i can check if a job is already enqueued or running so as to prevent further enqueueing?Dashboard
C
6

Every time you make that call, it will add another job to the DB. If you have that going on in Startup and your app frequently restarts, that will cause the behavior you're reporting. You could use the attribute DisableConcurrentExecution on your method call, or you can enter the jobinto the DB as a timed recurring job via Hangfire.RecurringJob.AddOrUpdate instead of BackgroundJob.Enqueue

Carbaugh answered 26/9, 2016 at 15:40 Comment(0)
B
1
   var options = new BackgroundJobServerOptions { WorkerCount =1 };
            app.UseHangfireServer(options);

I hope this will help you

Becket answered 25/10, 2016 at 1:56 Comment(3)
Can you please add more detail as to why this will solve the issue?Forever
when multiple threads visit the method at the same time,the method may be call more than once!Becket
you can refer to this :docs.hangfire.io/en/latest/background-processing/…Becket

© 2022 - 2024 — McMap. All rights reserved.