Salesforce Batch执行批次数量问题

324 阅读2分钟

创建一个Batch

global class SupportProductBatch implements Database.Batchable<sObject> {
    public String query;

    global AccountBatch() {
       this.query = 'SELECT Id FROM Support_Product__c';
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
        System.debug(LoggingLevel.INFO, '*** scope.size(): ' + scope.size());
    }

    global void finish(Database.BatchableContext BC) {

    }
}

创建测试数据

先将系统中的数据清空

DELETE [SELECT Id FROM Support_Product__c Limit  100 ];

创建500条数据

List<Support_Product__c> supls = new List<Support_Product__c>();
Integer i = 0;
while(i < 400){
	Support_Product__c sup = new Support_Product__c();
	sup.numberText__c = i + '';
	supls.add(sup);
	i++;
}
insert supls;

执行Batch

SupportProductBatch supportProductBatch = new SupportProductBatch();
DataBase.executeBatch(supportProductBatch,100);

image.png

可以看到数据量为400时,Batch的Size设置为100会执行4个批次

那数据量为500时那如果size设置为250,会有多少个批次呢?

List<Support_Product__c> supls = new List<Support_Product__c>();
Integer i = 0;
while(i < 100){
	Support_Product__c sup = new Support_Product__c();
	sup.numberText__c = i + '';
	supls.add(sup);
	i++;
}
insert supls;

SupportProductBatch a = new SupportProductBatch();
DataBase.executeBatch(a,250);

image.png 可以看到数据量为500时,Batch的Size设置为250会执行3个批次,按照猜想应该是2个批次那为什么最终是3个批次呢?

让我们将系统的数据量增加到2100

image.png

此时将Batch的size设置为700,预测是3个批次,那真的会是3个批次吗?让我们来测试

SupportProductBatch a = new SupportProductBatch();
DataBase.executeBatch(a,700);

image.png 可以看到却是4个批次

原因

  1. 1<=size<=100时,Batch中的检索块的大小是100,然后放到execute方法中进行执行
  2. 100<size<=400时,Batch中的检索块的大小是400,所以当500条数据批次大小是250时,首先会检索出400条,第一次执行处理250条数据,然后剩余150条数据,再用一个批次执行这150条数据,下一个检索块仍是400的大小,但是系统中还剩下100条会放在容量是400的检索块中再执行一个批次,
  3. 当400<size<=2000时,Batch中的检索块的大小是2000,所以当数据量是2100时,Batch的size设置为700时会执行4个批次道理同上

参考

docs.google.com/spreadsheet…