3

To provide a representative example, please consider the code below:

global class SampleJob implements Database.Batchable<sObject> {
    Boolean skipExecution;
    public SampleJob(Boolean skipExecution) {
        this.skipExecution = skipExecution;
    }
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, Name, Phone FROM Account';
        if(skipExecution) {
            return null;    
        }

        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Account> scope) {
        for (Account a : scope) {
            a.Phone='123';
        }
        update scope;
    }  
    global void finish(Database.BatchableContext BC){
        System.debug('In finish');
    }
}

This is only a representative example, in reality my condition for skipping execute will depend on many runtime factors.

If I invoke this code with Database.executeBatch(new SampleJob(false));, my job should run as usual. However if I pass true as a parameter instead, I want the job to skip the execute method and execute finish directly. This, however gives me a

System.UnexpectedException: Start did not return a valid iterable object.

Is there any way to return a valid 0 size iterable so that the execute method can be skipped?

1 Answer 1

6

In the condition, instead of returning null, add LIMIT 0 to the query.

Here is the updated start method:

global Database.QueryLocator start(Database.BatchableContext BC) {
    String query = 'SELECT Id, Name, Phone FROM Account';
    if(skipExecution) {
        query += ' LIMIT 0';    
    }

    return Database.getQueryLocator(query);
}
0

You must log in to answer this question.

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