5

I have a batch and now I want to create a schedulable class to run the batch every Saturday at 1AM. I was following the salesforce docs but cannot seem to grasp everything correctly.

Here's my schedulable class code

global class SchedulableClass implements Schedulable {
    global void execute(SchedulableContext sc) {
        IndependentBatch b = new IndependentBatch();
        database.executebatch(b);
    }
    SchedulableClass saturday1am = new SchedulableClass();
    String sch = '0 0 01 ? * 7';
    String jobId = system.schedule('sat1am', sch, saturday1am);
}

How do I activate this class? Is my syntax correct? Am I supposed to move the string sch and system.schedule inside the execute? If so do I remove the database.executebatch(b) in this case?

6

This code:

SchedulableClass saturday1am = new SchedulableClass();
String sch = '0 0 01 ? * 7';
String jobId = system.schedule('sat1am', sch, saturday1am);

Needs to be outside of that class, since that is the code that schedules your job.

You can either put that code inside another class, or run it from "Execute Anonymous".

  • 1
    I would add to this. Or simply schedule it through the system interface. Setup => Develop => Apex Classes => Schedule Apex. – Jesse Milburn Mar 1 '16 at 17:19
  • Where do I put that code inside the rest of my apex code? Do I put it in the controller of the visualforce page? – Arthlete Mar 1 '16 at 17:19
  • @JesseMilburn - thanks for the suggestion. I already researched that, now I wanted to see how I can do it with strictly apex code as well. Thank you. – Arthlete Mar 1 '16 at 17:19
  • 2
    The Controller of a VF page is a perfect place for it, I would hook it up to a button (so a user can click something to schedule it) – Sebastian Kessel Mar 1 '16 at 17:20
  • 2
    You're welcome! If it works for you, make sure to mark the solution as accepted so others can benefit! – Sebastian Kessel Mar 1 '16 at 17:21
4

Just a note, you can implement Schedulable in the same class as your Batchable. No need to write them separately.

public class MySchedulableBatch implements Schedulable, Database.Batchable<SObject>
{
    public void execute(SchedulableContext sc) { Database.executeBatch(this); }
    // Database.Batchable implementation
}
  • 1
    Man, that's beautiful. Thank you for letting me know! – Arthlete Mar 1 '16 at 17:35

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.