0

Here's a use case I'm trying to figure out for while:

I run the following batch class to update records:

MyBatchClass batchInstance = new MyBatchClass ();
database.executeBatch(batchInstance ,1);

The above code always runs from Developer Console. This code needs a delay timer of 2 minutes because if it does updates an existing record, they might lockout. Can I do this without a Scheduler or without creating a custom object? I would need the last run apex batch job. I tried the below not so generic code:

AsyncApexJob aaj1 =[ SELECT Id, CreatedDate, CreatedById, JobType, ApexClassId, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors, CompletedDate, MethodName, ExtendedStatus, ParentJobId, LastProcessed, LastProcessedOffset FROM AsyncApexJob where CompletedDate !=null order by CompletedDate desc limit 1];


if(System.now().minute() - aaj1.CompletedDate.minute()>120 && aaj1.ApexClassId =='01p01e21321318digit') 
{
MyBatchClass  b = new MyBatchClass ();
database.executeBatch(b,1);
} 
 else{
System.debug('Batch already ran or in In progress status, Please wait for 120 seconds')
}

I couldn't proceed with the following because I would already have to execute the batch in order for me to get the batch job Id (batchprocessid )

  >Id batchprocessid = Database.executeBatch(new MyBatchClass, 200); 
   >AsyncApexJob aaj = [SELECT Id, CreatedDate, CreatedById, JobType, ApexClassId, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors, CompletedDate, MethodName, ExtendedStatus, ParentJobId, LastProcessed, LastProcessedOffset FROM AsyncApexJob WHERE ID =: batchprocessid ];                 

Is there any better way to do it? I didn't run the above code as it's on sensitive data and didn't want to take any chance. Any suggestion or guidance would be appreciated.

Thanks in advance!

1
  • If if it does updates an existing record, they might lockout is a problem statement, there may be solutions other than a delay. SELECT...FOR UPDATE might be one.
    – identigral
    Commented Apr 16, 2020 at 18:14

1 Answer 1

3

System.scheduleBatch can do that. It takes three or four parameters. The batch to execute (required), the name of the job (required), the delay in minutes (required), and the scope size (optional, default 200). If you want this on repeat, call System.scheduleBatch in the finish method of your batch. This will give you two minutes between the end of the first batch and the start of the next.

3
  • Thanks for the answers. Good to see your answers after a long time. As I mentioned, is there any other way without a scheduler!
    – MnZ
    Commented Apr 16, 2020 at 19:06
  • 1
    @MnZ The scheduleBatch method doesn't need a scheduler to work, as it provides one for you.
    – sfdcfox
    Commented Apr 16, 2020 at 19:08
  • This is something new I learnt today. Thanks!
    – MnZ
    Commented Apr 17, 2020 at 4:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .