[Salesforce] Apex Batch Class

hyunsooSong·2022년 10월 11일
0

Salesforce

목록 보기
10/13
post-thumbnail

✏️ Apex Batch Class

deafult batch size == 200


1. Batch Class

📰 full structures

implements Database.Batchable<>

global class MyBatchClass implements Database.Batchable<sObject> {
    global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
    }
    global void execute(Database.BatchableContext bc, List<P> records){
        // process each batch of records
    }    
    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }    
}

1) start(Database.BatchableContext bc)

  • batch class 호출 시 처음 한 번 호출되는 메소드
  • 반환 값
    1) Database.QueryLocator
    : SOQL 쿼리에 의해 검색되는 총 레코드 수에 대한 governor limit이 무시되고 최대 5천만 개의 레코드를 쿼리할 수 있습니다.

    2) Iterable
    : SOQL 쿼리에서 검색한 총 레코드 수에 대한 governor limit이 계속 적용됩니다.

배치 할 instance Database.getQueryLocator(query)로 반환

global Database.QueryLocator start(Database.BatchableContext BC) {
	String query = 'SELECT Id, Name FROM Account';
	return Database.getQueryLocator(query);
}

2) execute(Database.BatchableContext bc, List<> records)

  • start()에서 반환한 instance들을 이용해서 작업 수행
  • 배치는 start 메서드에서 받은 순서대로 실행되지 않음 (순서 보장 X)

List<>로 start() 반환 값 넘어옴

global void execute(Database.BatchableContext BC, List<Account> accList) {
     // process each batch of records default size is 200
      for(Account acc : accList) {     
          acc.Name = acc.Name + 'sfdcpoint';
      }
      try {
          update accList;
      } catch(Exception e) {
          System.debug(e);
      }
}   

3) finish(Database.BatchableContext bc)

모든 배치가 처리된 후 한 번 호출


2. Batch Class 호출

  • 배치 작업 실행
    : Database.executeBatch( )의 매개변수로 내가 만든 배치클래스 객체를 넘긴다.

  • Batch 작업 진행상황 추적
    : AsyncApexJob Object에서 Database.executeBatch()로 반환된 batchId를 이용해서 진행 상황 추적
MyBatchClass myBatchObject = new MyBatchClass(); 
Id batchId = Database.executeBatch(myBatchObject);
Id batchId = Database.executeBatch(myBatchObject, 100); // batch size change

// Batch 작업 진행상황 추적
AsyncApexJob job = [
	SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors 
    FROM AsyncApexJob 
    WHERE ID = :batchId ];

3. Batch Apex Scheduling

  • Salesforce setting -> Apex Class -> Schedule Apex -> 스케줄 등록

implements Schedulable

global class scheduledBatchable implements Schedulable {
   global void execute(SchedulableContext sc) {
      BatchApexExample b = new BatchApexExample(); 
      Database.executeBatch(b);
   }
}

4. Test Batch Class

  • testMethod 내에서 2개 이상의 executeBatch를 호출할 수 없기 때문에, 200개 이상의 레코드를 처리할 때 오류 나타남.
    ➡️ 해결방법
    1) test data를 200개 이하로 생성

    2) Test.isRunningTest 사용
    ※ 주의
    만약 batch를 100개로 설정하였다면 100개 이하로 생성해야함
@isTest
private class BatchApexExampleTest {
    static testmethod void test() {
        // Create test accounts to be updated by batch
    Account[] accList = new List();
    for (Integer i=0;i<100;i++) {
        Account ac = new Account(Name = 'Account ' + i);
        accList.add(ac);
    }
    insert accList;
 
        Test.startTest();
            BatchApexExample b = new BatchApexExample();
        	Database.executeBatch(b);
        
        	// if use scheduling at batch class
        	String CRON_EXP = '0 0 9 * * ? *';
        	System.schedule('scheduledBatchable_test', CRON_EXP, new scheduledBatchable());
        Test.stopTest();
        // Verify accounts updated
    Account[] accUpdatedList = [SELECT Id, Name FROM Account];
    System.assert(accUpdatedList[0].Name.Contains('sfdcpoint'));
    }
}
profile
🥕 개발 공부 중 🥕

0개의 댓글