[SalesForce] Apex Batch class without passing any SOQL

I have simple requirement to insert number of Accounts.
Now what I noticed to call the following I have to pass SOQL which is irrelevant since there will be no use of the result of this query

Please suggest how can I call batch apex without passing SOQL.

Database.executeBatch(new BatchAccountsProcess('Select id from Account limit 1'));

 global class BatchAccountsProcess .... {

  global BatchAccountsProcess(String qryStr)
 {
     Query = qryStr;
 } 

 global Database.QueryLocator start(Database.BatchableContext BC)
 {
     return Database.getQueryLocator(query);
 }
 global void execute(Database.BatchableContext BC,List<sObject> scope)
 {
       for(integer iAcc = 0 ;iAcc < 5000 ; iAcc++) {
        Account accObj =  new Account(name='Arijit_batch_'+iAcc);
        lstAccount.add(accObj);
    }         
      Database.insert(lstAccount);
  }

}

Best Answer

You can create a number of records like so:

public class CreateAccountsBatch implements Database.Batchable<Account>, Iterable<Account>, Iterator<Account> {
    Integer counter = 0, max;
    // How high to count to
    public CreateAccountsBatch(Integer max) {
        this.max = max;
    }
    // Iterator to use
    public Iterator<Account> iterator() {
        return this;
    }
    // Get next account record in iterator
    public Account next() {
        return new Account(Name='Arijit_batch_'+counter++);
    }
    // Any more accounts to do
    public Boolean hasNext() {
        return counter < max;
    }
    // Database.Batchable start method
    public Iterable<Account> start(Database.BatchableContext context) {
        return this;
    }
    // Database.Batchable execute method
    public void execute(Database.BatchableContext context, Account[] scope) {
        insert scope;
    }
    // Database.Batchable finish method
    public void finish(Database.BatchableContext context) {

    }
}

Which you can then call as:

Database.executeBatch(new CreateAccountsBatch(5000));
Related Topic