Richa Garg
Richa Garg

Reputation: 1926

Hangfire : How to stop processing of background jobs and process them in a certain time period

We have a scenario where we want the jobs to keep on queuing in the server but not processing. Processing of jobs should be done in a specific time period for e.g., 11 am to 13 pm. For recurring jobs, this can be done by using CRON expressions. Is there any way we can achieve the same thing with Background jobs enqueued.

For normal processing, we are queuing in user-defined queues as :

var state = new EnqueuedState(queue.Name);
_client.Create(methodCall, state);

_client is of type IBackgroundJobClient.

Upvotes: 0

Views: 883

Answers (1)

Marko Papic
Marko Papic

Reputation: 1916

You can schedule a background job from another background job. So, you could maybe put the scheduling decision logic inside the method you are scheduling.

Say you have the following method:

void DoSomethingAndScheduleAgain()
{
   // Do some work...

   bool shouldContinue = //Some condition (e.g. it is not 13 pm yet)
   if (shouldeContinue)
      BackgroundJob.Schedule(DoSomethingAndScheduleAgain), TimeSpan.FromMinutes(5));
   else
      BackgroundJob.Schedule(DoSomethingAndScheduleAgain), TimeSpan.FromHours(22)); //Wait until tomorrow
}

Now you just schedule this method for the first time and the method will continue scheduling itself when needed.

BackgroundJob.Schedule(DoSomethingAndScheduleAgain), TimeSpan.FromMinutes(1));

Upvotes: 1

Related Questions