function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Steve BerleySteve Berley 

Limit so only one user can run batch at a time?

Hi,

I have a client who has a batch process that generates a lot of data, and because of this it takes a bit to run.

Since the process needs to be manually triggered, is it possible to prevent someone from starting it if another user already has it running?

Could I query active jobs and throw a message if it's in queue?

Thanks,

Steve 
Best Answer chosen by Steve Berley
David Zhu 🔥David Zhu 🔥
You may refer to the following code to check if the same batch is in process and skip it if same batch is existing.
global Database.QueryLocator start(Database.BatchableContext bc) { 
List<AsyncApexJob> jobs = [Select Id, Status, methodname,ApexClassId,apexClass.Name from AsyncApexJob
Where apexClass.Name = 'yourclassname' and Status in ('Queued','Preparing','Processing')];   //replace yourclassname with your actual class name

  If (jobs.size() = 0) 
  {
     return Database.getQueryLocator(query);
  }
}


 

All Answers

AnudeepAnudeep (Salesforce Developers) 
With the below SOQL query, you will get the active jobs. Based on the results of this query, you can handle your code
 
SELECT COUNT() FROM AsyncApexJob WHERE JobType='BatchApex' AND Status IN ('Processing','Preparing','Queued')

I recommend looking at the following example

Anudeep
David Zhu 🔥David Zhu 🔥
You may refer to the following code to check if the same batch is in process and skip it if same batch is existing.
global Database.QueryLocator start(Database.BatchableContext bc) { 
List<AsyncApexJob> jobs = [Select Id, Status, methodname,ApexClassId,apexClass.Name from AsyncApexJob
Where apexClass.Name = 'yourclassname' and Status in ('Queued','Preparing','Processing')];   //replace yourclassname with your actual class name

  If (jobs.size() = 0) 
  {
     return Database.getQueryLocator(query);
  }
}


 
This was selected as the best answer
Steve BerleySteve Berley
thanks all for the super fast help!!!