Way to get the batch size that a BatchableContext was called with, from within the batch?

It's not ideal, but you could just pass the desired batch size for the scope parameter into the Batch constructor - See Passing Parameter to batch apex.

Another slight variation of that is to use Database.Stateful and then set a member variable to the largest size of the list you encounter in the execute method. As sfdcfox commented, if there aren't more than the scoped number of records then the count you get will be smaller than the scope. If you are chaining them then you might eventually end up with a scope of 1.

If you don’t specify Database.Stateful, all static and instance member variables are set back to their original values.
Source


I've done this in a chained batchable before:

public class MyBatchable implements Database.Batchable<SObject>, Database.Stateful {

    private Integer batchSize;

    public MyBatchable(Integer batchSize, ...) {
        this.batchSize = batchSize;
    }

    ...

    public void finish(Database.BatchableContext bc) {
        Database.executeBatch(new MyBatchable(batchSize, ...));
    }
}

Tags:

Apex

Batch