1

I feel like i'm missing something basic here, I wrote a batch class that should be scheduled to run daily at a certain time of the day, forever.

Do I really have to create an additional class that implements schedulable + a test class just to run it once? Am I missing something? Is this my only option here?

I thought System.scheduleBatch method might be helpful but according to the docs it only runs once.

2
  • well you're not creating the additional schedulable class just to run it once...you're creating it so it runs on a schedule - in this case, daily. Or am I missing something? – Kris Goncalves Jan 13 at 16:38
  • I imagine using a cron expression to set it to run daily. – Json Jan 13 at 16:48
2

If you want to schedule apex within Salesforce, you need to implement Schedulable - even if it is just to run daily. Then, you can write a cron expression to schedule it how you'd like or use the UI to schedule it as well.

There's also now Scheduled Flows which presents another option although I believe it's limited to 250,000 flow interviews a day so you need to take that into account.

For your question, you could create a separate class to handle scheduling or you could have the same class that's implementing Database.BatchableContext implement Schedulable. You'd do something like this:

public class BatchSchedulableClass implements Schedulable, Database.Batchable<sObject> {

    public String Query;

    public BatchSchedulableClass(){
        Query = 'SELECT Id FROM Account';
    }

    //for the schedulable to execute the batch class (this class)
    public void execute(SchedulableContext ctx){
        Id batchJobId = Database.executeBatch(this,100);
    }
   
    
    public Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext BC, List<sObject> scope){
        //do logic here
    }

    public void finish(Database.BatchableContext BC){
        //do any finishing for the batch job here
    }
}
4
  • public, not global is preferred – cropredy Jan 14 at 0:48
  • good catch, I was just copying from the docs which use global. Updated – Kris Goncalves Jan 14 at 0:52
  • yeah - those docs have led to many going astray over many years – cropredy Jan 14 at 0:52
  • thank you, I will try to implement the two interfaces. – Json Jan 14 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.