18

Is there a way to pass a parameter into a schedulable class execute method? We were trying to pass a string from another scheduled class into this scheduled class but it looks like we can't do that?

As quick context we have the scheduled date and time as a record in a custom object so we are trying to pass that info into our scheduled class.

global class MturkVSSchedule implements Schedulable{

    global void execute(SchedulableContext SC, **String s**){

Putting String S throws a compile error. Is there a different way that I'm missing?

0

4 Answers 4

24

What about passing parameters through constructor and storing them in instance variables?

public class Dummy_Schedulable_Class implements Schedulable{

    public List<String> names;
    public List<String> cronExpressions;

    public void execute(SchedulableContext SC) {
        System.debug(LoggingLevel.ERROR, names );
        System.debug(LoggingLevel.ERROR, cronExpressions );
        testScheduleClassMethod(names[0]);
    }

    public void testScheduleClassMethod(string argPass){

    }

    public Dummy_Schedulable_Class ( List<String> aNames, List<String> aCronExps) {
        if ( names == null ) {
            names = aNames;
        } else {
            names.addAll(aNames);
        }
        if ( cronExpressions == null ) {
            cronExpressions = aCronExps;
        } else {
            cronExpressions.addAll(aCronExps);
        }
    }

}

And whenever you need to pass parameters you can do the following:

System.schedule('test', '0 47 18 * * ?', new Dummy_Schedulable_Class(new String[]{'a','b'}, new String[]{'c','d'}));

Please mark this answer as accepted or vote up if you agree that it answers your question.

5
  • I just tried this. I haven't finished my testing, but the parameter passing by way of the constructor appears to be working.
    – Jagular
    Jun 2, 2014 at 20:30
  • @Jagular I'm glad this helped to you
    – Patlatus
    Jun 4, 2014 at 7:08
  • @Patlatus It Worked...ThankYou!!!
    – A.Bretto
    Jun 25, 2018 at 7:00
  • No need to use global access modifier.
    – Phil W
    Jan 22, 2020 at 23:17
  • @PhilW yes, agree
    – Patlatus
    Jan 28, 2020 at 10:57
9

There is no way to pass information in an Apex sense.

Passing Information to Schedulable Job using a Custom Object.

You can pass information via the database, the basic steps are this...

  1. Use the Id returned from the System.schedule method
  2. After scheduling the job insert a record into a Custom Object (e.g. Schedule Info) that contains the information you want the job to read when it executes. Being sure to also store the job Id on the record.
  3. Then in the execute method use the SchedulableContext.getTriggerId (confusing name i know) method to obtain the job Id and query the record previously written for the information needed.
  4. You should consider putting in a try/finally some cleanup code to delete the record once the execute completes.

Apologies for not giving a code sample here, let me know if you need one and I can work one up.

NOTE: You may also want to consider using a List type protected Custom Setting, which has the benifit of saving DML, SOQL and is hidden from the end users.

2
  • loved the concept of using object as variable ! Jul 27, 2013 at 9:00
  • ha, thanks, i've not tried using this approach with a custom setting before, maybe a blog one day... :) Jul 29, 2013 at 8:41
2

I use generally use a static variable (as seen below), and pass that into a system.schedule call, but there's no reason you cant query the database to construct the string instead. I hope this helps

global class ScheduledJob implements Schedulable {

    public static String Sched = '0 00 22 * * ?';  //Every Day at 10PM 
    //I use a set schedule, you can instead query your custom object below      

    global static String scheduleThisJob() {

        object object = [Select Id, Name From Custom_Object__c];
        Sched =  ?? //use the object above to construct the chron for the scheduled job

        ScheduledJob SJ= new ScheduledJob(); 
        return System.schedule('My Scheduled Job', Sched, SJ);
    }

    global void execute(SchedulableContext sc) {

        BatchActiveMemberCheck BatchActive = new BatchActiveMemberCheck(ActiveMemberCheckUtililty.activeContactIDs());
        ID batchprocessid = Database.executeBatch(BatchActive,50);      
    }


}
1
  • Originally I was trying to pass the scheduling string into the execute method which is where I was having problem. We have 1 scheduled class which say runs once per day, and that is supposed to create multiple other scheduled classes. So the execute method was to receive the string you reference so it can pass those off to the other scheduled method. But trying to see if we can use what you posted and accomplish this another way? So if my object has 10 items to be scheduled at various times today, we wanted to do that. Different times, or none, tomorrow, etc.
    – ddeve
    Jul 26, 2013 at 19:57
0

Here's my way of passing parameters to a schedulable apex class.

This following class has a constructor that takes two parameters and sets the class attributes to hold the values passed into as the arguments and creates an instance object of the class which will contain the class attributes as well as the class methods. Here we have one method called main (note: this is an arbitrary name).

The execute method is the Schedulable interface's method which needs to be specified because we're implementing the interface and this method calls the instance object's main method which can use the passed-in arguments that have been saved into the object's attribute variables.

public with sharing class CronJob_That_Takes_Parameters implements Schedulable {
    String aString; Integer toBeCalculated;
    @testVisible Integer anInteger; // tip: use @testVisible annotation if you want to avoid hard coding values in the unit test

    public void execute(SchedulableContext ctx) {
        this.main(); // invoke the main method from this schedulabel execute method
    }

    // this is the class constructor
    public CronJob_That_Takes_Parameters(String aString, Integer anInteger) {
        this.aString = aString;
        this.anInteger = anInteger;
        this.toBeCalculated = this.anInteger * this.aString.size() /* you can also use custom settings and/or custom metadata values here */;
    }

    // put in the code for the main process
    public void main() {
        try {
            // main logic

        } catch (Exception ex) {
            // error handling
        }
    }
}

in order to schedule this class use the following code.

    // schedule the cron job
    String aString = 'String value argument', cronExp = '0 0 6 ? * MON-FRI'; // every weekday at 6am
    Integer anInteger = 10;
    CronJob_That_Takes_Parameters cronJob = new CronJob_That_Takes_Parameters(aString, anInteger);
    System.schedule('cron job name goes here!', cronExp, cronJob);
2
  • Thanks for your contribution, but this answer can attract down votes or be flagged because it is pratically a duplicate of the most voted answer back in 2014.
    – Shamina
    May 25 at 10:48
  • @Shamina it's the same way to solve the issue. I have seen similar answers in SE. Why would I get down/flagged when providing clean understandable answer which obviously is not a copy of the most voted answer. IHO my answer is a bit more clear to understand and has a couple of tips and more explanation for beginners.
    – Bahman.A
    May 25 at 16:01

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.