+ Start a Discussion
Savvy AdminSavvy Admin 

How to make scheduled batch class to queue?

There is a callout that needs batch class to execute. In the trigger, it will executed by

Database.executeBatch(new batchCallout(parameters),2000);

However, it occassionally reaches the 100 limit for "holding" status (Apex Flex Queue). Then to make it not reaching the limit, I did:

public static void scheduleBatch( parameters){
        batchCallout baltc = new batchCallout (parameters);
        system.scheduleBatch(baltc,'batchCallout', 30, 2000);

in the batch class and in the trigger:

if ([SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex' AND (Status = 'Holding')] < 100){ 
                    Database.executeBatch(new batchCallout(parameters),2000);
                } else {

Therefore, when the limit is reached, the new tasks will be scheduled 30 minutes later.

However, in the reality, when people have changed the record of this object and the batch job is scheduled. The same record of the object cannot be changed again. Otherwise, the system will throw the exception:

trgAfterIU: execution of AfterUpdate

caused by: System.AsyncException: The Apex job named "batchCallout" is already scheduled for execution.

First of all, my explanation about it is that when the scheduled job is created, the same record cannot be changed until the scheduled job is done.
However, when the tasks was queued in Apex Flex queue, this kind of situation would never happen.
Therefore, I conclusion is that I should make the scheduled job to be in a queue. When a scheduled job is created, the next new scheduled job on the same record should be able to queue after that job to solve this problem.

My question is, how to queue the scheduled job so the collision I described above won't happen again?
Best Answer chosen by Savvy Admin
Savvy AdminSavvy Admin
So far, I guess this problem is caused by "system.scheduleBatch(baltc,'batchCallout', 30, 2000);" where it defined the scheduled job in a constant name. However, every scheduled job has to have unique name. Now I have added the system time to the scheduled job's name. Later will see whether this problem is solved or not.