How to create thousands of records using batch apex

So as written, that doesn't really operate as a batch should - the batch just calls the one method and tries to create all the records in one execution...a batch is designed to run as a series of iterations. I think what you need is a batch that uses a custom iterator - so take a look at this StackEx post. In that example, they use a String Iterator, but I think you need to use an Integer Iterator, or maybe main state and keep count.

Essentially, you need the batch to only create ~200 accounts per execution to stay within the limits

Here's a better formatted version of SFDCFox's example:

Basic iterator:

public class IntegerIterator implements Iterable<Integer>, Iterator<Integer> { 
Integer counter; 

public IntegerIterator(Integer counter) {
 this.counter = counter; 
} 

public Boolean hasNext() { return counter > 0; } 

public Integer next() { return counter--; } 

public Iterator<Integer> iterator() { return this; } 
} 

In the start method, just return a value to count to: return new IntegerIterator(1000);

*****Edit***** And then the batch would look something like this:

public class AccountBatchUpdate implements Database.batchable <Integer> { 

   public Iterable<Integer> start(Database.batchableContext info){ 
       return new IntegerIterator(1000);   
   } 

   public void execute(Database.batchableContext info, List<Integer> scope){ 
   //Loop through integer list and create records
   }

   public void finish(Database.batchableContext info){     

   }
}

Tags:

Dml

Apex

Batch