Inspect job before dequeuing

I understand that I’m able to be notified before a job is processed through the IServerFilter method OnPerforming. But am I able to cancel processing without cancelling the job?

As an example, lets say I have multiple hangfire servers running, all eating from the same queue. The servers are running in different locations, so when a server is grabbing a job, I want to inspect and see if this server should process the job, or if it should better leave it on the queue for someone else to process.

Of cause, this scenario might be better solved with multiple queues, but I still wan’t to know if it’s possible…

I think I found the solution for this.

By implementing the IElectStateFilter, I’m able to manipulate the state-transition, e.g.

            public void OnStateElection(ElectStateContext context)
            {   
                if (context.CurrentState == EnqueuedState.StateName)
                {
                    context.CandidateState = new EnqueuedState() {Reason = "Lets do this another time....."};
                }
            }

The dashboard will reflect that re-enqueuing, showing the reason.
I’m not sure how different queues are handled, though. I guess the job will move to the default queue if it’s not already there. But this is the best way I’ve found so far.

I looks like the first approach didn’t work out as well as I had hoped…

When a job comes from EnqueuedState and is then put into EnqueuedState again, I end up having the job duplicated in the queue, which again makes the dashboard choke…

So my new approach is to schedule the job for later execution:

            public void OnStateElection(ElectStateContext context)
            {   
                if (context.CurrentState == EnqueuedState.StateName)
                {
                    context.CandidateState = new ScheduledState(TimeSpan.FromSeconds(1)) {Reason = "Lets do this another time....."};
                }
            }

I thought I had this working earlier, though…

Under certain conditions, I also shut down hangfire al together, by triggering the cancellation token.

Could it be that causing the duplicated entry?
How will hangfire react if its asked to cancel what it’s doing in the middle of moving a job from one state to another? Will it put the job back on the queue even though it’s already heading that way?