When is a batch class instantiated when you schedule it?












1















QUESTION: when you instantiate a class in a scheduled apex job, is the class instantiated at the time of the schedule, or at the scheduled time of execution?



Here's my situation...
I have a custom object called Blast, which schedules a bulk SMS send. That object record includes a DateTime field that designates when the blast will happen; for this example, let's say the blast happens next Tuesday at 1:00 pm.



The blast has some unknown number of recipients -- very possibly 20-50k, which are stored as CampaignMembers. So, at the designated time, I have a batch apex class that retrieves all of the recipient info from the CampaignMember records and makes the api call.



When a user creates/updates the Blast record today and sets status to "queued", I'm creating a scheduled apex job, instantiating my batch apex class and providing the blast record, from which it pulls necessary data.



I want to build into the batch apex class a check that verifies the blast record still exists before executing the blast. But I'm not clear on whether that class is instantiated today (when the job is scheduled), or next Tuesday at 1:00pm when it has been scheduled to run.










share|improve this question



























    1















    QUESTION: when you instantiate a class in a scheduled apex job, is the class instantiated at the time of the schedule, or at the scheduled time of execution?



    Here's my situation...
    I have a custom object called Blast, which schedules a bulk SMS send. That object record includes a DateTime field that designates when the blast will happen; for this example, let's say the blast happens next Tuesday at 1:00 pm.



    The blast has some unknown number of recipients -- very possibly 20-50k, which are stored as CampaignMembers. So, at the designated time, I have a batch apex class that retrieves all of the recipient info from the CampaignMember records and makes the api call.



    When a user creates/updates the Blast record today and sets status to "queued", I'm creating a scheduled apex job, instantiating my batch apex class and providing the blast record, from which it pulls necessary data.



    I want to build into the batch apex class a check that verifies the blast record still exists before executing the blast. But I'm not clear on whether that class is instantiated today (when the job is scheduled), or next Tuesday at 1:00pm when it has been scheduled to run.










    share|improve this question

























      1












      1








      1








      QUESTION: when you instantiate a class in a scheduled apex job, is the class instantiated at the time of the schedule, or at the scheduled time of execution?



      Here's my situation...
      I have a custom object called Blast, which schedules a bulk SMS send. That object record includes a DateTime field that designates when the blast will happen; for this example, let's say the blast happens next Tuesday at 1:00 pm.



      The blast has some unknown number of recipients -- very possibly 20-50k, which are stored as CampaignMembers. So, at the designated time, I have a batch apex class that retrieves all of the recipient info from the CampaignMember records and makes the api call.



      When a user creates/updates the Blast record today and sets status to "queued", I'm creating a scheduled apex job, instantiating my batch apex class and providing the blast record, from which it pulls necessary data.



      I want to build into the batch apex class a check that verifies the blast record still exists before executing the blast. But I'm not clear on whether that class is instantiated today (when the job is scheduled), or next Tuesday at 1:00pm when it has been scheduled to run.










      share|improve this question














      QUESTION: when you instantiate a class in a scheduled apex job, is the class instantiated at the time of the schedule, or at the scheduled time of execution?



      Here's my situation...
      I have a custom object called Blast, which schedules a bulk SMS send. That object record includes a DateTime field that designates when the blast will happen; for this example, let's say the blast happens next Tuesday at 1:00 pm.



      The blast has some unknown number of recipients -- very possibly 20-50k, which are stored as CampaignMembers. So, at the designated time, I have a batch apex class that retrieves all of the recipient info from the CampaignMember records and makes the api call.



      When a user creates/updates the Blast record today and sets status to "queued", I'm creating a scheduled apex job, instantiating my batch apex class and providing the blast record, from which it pulls necessary data.



      I want to build into the batch apex class a check that verifies the blast record still exists before executing the blast. But I'm not clear on whether that class is instantiated today (when the job is scheduled), or next Tuesday at 1:00pm when it has been scheduled to run.







      schedulebatch






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 2 hours ago









      PatMcClellan__cPatMcClellan__c

      791220




      791220






















          2 Answers
          2






          active

          oldest

          votes


















          3














          It's instantiated when new SomeBatchJobName() is called, then serialized when System.scheduleBatch(...) is called. So the data stored in the object will be from the moment of instantiation (now), not when it is eventually pulled from the queue and executed. This is also true for scheduled and queueable jobs, too.






          share|improve this answer
























          • OK, thanks. That's what I thought would happen, just wanted to confirm. So that means any changes (between now and next Tuesday) to the data I use to instantiate the object will not be reflected. So... I'm thinking I need another class, that executes next Tuesday and instantiates the batch object then.

            – PatMcClellan__c
            2 hours ago











          • @PatMcClellan__c Without seeing your code, hard to say, but remember you can also do other stuff in your start method besides just providing a query locator. During the start method might be a perfect time to do any other calculations or queries you need to perform to see if you want to continue or not. You can also use System.abortJob in the start method if you want to cancel your job early (the job Id comes from the BatchableContext object).

            – sfdcfox
            2 hours ago











          • Ah... I was wondering about that. So, instead of providing the entire blast record when I instantiate, I just provide the recordId. Then, in the start method, I do a soql search on it, pull the data at that point in time, or abort if the record no longer exists.

            – PatMcClellan__c
            1 hour ago











          • @PatMcClellan__c Yes, you should always query for the data you're going to work on as late as possible, especially when using asynchronous code that might not be called for a long time.

            – sfdcfox
            1 hour ago











          • I can't find docs on how to pull the jobId while inside the start method. Would it be something like... BC.getJobId() ?

            – PatMcClellan__c
            1 hour ago





















          0














          For the benefit of clarity, I'll share my revised code... the object is actually called Wave, not Blast.



          global class QueueWave implements Database.Batchable<SObject>, Database.Stateful {
          global String waveId;
          global String body;
          global String messageServiceLabel;
          global Integer recipientCount;
          global String emailAddress;
          global String waveName;
          global String userId;

          global QueueWave(String waveId) {
          this.waveId = waveId;
          }


          The constructor does nothing except store the recordId at the time this batch class is scheduled. I'm using try-catch, catching QueryException which aborts the job.



          global Database.QueryLocator start(Database.BatchableContext BC){
          if(Wave__c.SObjectType.getDescribe().isAccessible()){
          try{
          Wave__c wave = [
          SELECT [fields I need, which may have been updated since batch was scheduled]
          FROM Wave__c
          WHERE Id = :this.waveId
          LIMIT 1];

          //set global vars with data from the wave record
          . . .

          String query = // build my query string here
          return Database.getQueryLocator(query);

          }catch(QueryException qe){
          System.debug('QueryException on ' + BC.getJobId() + ' ' + qe);
          System.abortJob(BC.getJobId());
          }
          }
          }





          share|improve this answer























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "459"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f253757%2fwhen-is-a-batch-class-instantiated-when-you-schedule-it%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            It's instantiated when new SomeBatchJobName() is called, then serialized when System.scheduleBatch(...) is called. So the data stored in the object will be from the moment of instantiation (now), not when it is eventually pulled from the queue and executed. This is also true for scheduled and queueable jobs, too.






            share|improve this answer
























            • OK, thanks. That's what I thought would happen, just wanted to confirm. So that means any changes (between now and next Tuesday) to the data I use to instantiate the object will not be reflected. So... I'm thinking I need another class, that executes next Tuesday and instantiates the batch object then.

              – PatMcClellan__c
              2 hours ago











            • @PatMcClellan__c Without seeing your code, hard to say, but remember you can also do other stuff in your start method besides just providing a query locator. During the start method might be a perfect time to do any other calculations or queries you need to perform to see if you want to continue or not. You can also use System.abortJob in the start method if you want to cancel your job early (the job Id comes from the BatchableContext object).

              – sfdcfox
              2 hours ago











            • Ah... I was wondering about that. So, instead of providing the entire blast record when I instantiate, I just provide the recordId. Then, in the start method, I do a soql search on it, pull the data at that point in time, or abort if the record no longer exists.

              – PatMcClellan__c
              1 hour ago











            • @PatMcClellan__c Yes, you should always query for the data you're going to work on as late as possible, especially when using asynchronous code that might not be called for a long time.

              – sfdcfox
              1 hour ago











            • I can't find docs on how to pull the jobId while inside the start method. Would it be something like... BC.getJobId() ?

              – PatMcClellan__c
              1 hour ago


















            3














            It's instantiated when new SomeBatchJobName() is called, then serialized when System.scheduleBatch(...) is called. So the data stored in the object will be from the moment of instantiation (now), not when it is eventually pulled from the queue and executed. This is also true for scheduled and queueable jobs, too.






            share|improve this answer
























            • OK, thanks. That's what I thought would happen, just wanted to confirm. So that means any changes (between now and next Tuesday) to the data I use to instantiate the object will not be reflected. So... I'm thinking I need another class, that executes next Tuesday and instantiates the batch object then.

              – PatMcClellan__c
              2 hours ago











            • @PatMcClellan__c Without seeing your code, hard to say, but remember you can also do other stuff in your start method besides just providing a query locator. During the start method might be a perfect time to do any other calculations or queries you need to perform to see if you want to continue or not. You can also use System.abortJob in the start method if you want to cancel your job early (the job Id comes from the BatchableContext object).

              – sfdcfox
              2 hours ago











            • Ah... I was wondering about that. So, instead of providing the entire blast record when I instantiate, I just provide the recordId. Then, in the start method, I do a soql search on it, pull the data at that point in time, or abort if the record no longer exists.

              – PatMcClellan__c
              1 hour ago











            • @PatMcClellan__c Yes, you should always query for the data you're going to work on as late as possible, especially when using asynchronous code that might not be called for a long time.

              – sfdcfox
              1 hour ago











            • I can't find docs on how to pull the jobId while inside the start method. Would it be something like... BC.getJobId() ?

              – PatMcClellan__c
              1 hour ago
















            3












            3








            3







            It's instantiated when new SomeBatchJobName() is called, then serialized when System.scheduleBatch(...) is called. So the data stored in the object will be from the moment of instantiation (now), not when it is eventually pulled from the queue and executed. This is also true for scheduled and queueable jobs, too.






            share|improve this answer













            It's instantiated when new SomeBatchJobName() is called, then serialized when System.scheduleBatch(...) is called. So the data stored in the object will be from the moment of instantiation (now), not when it is eventually pulled from the queue and executed. This is also true for scheduled and queueable jobs, too.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 2 hours ago









            sfdcfoxsfdcfox

            259k12204447




            259k12204447













            • OK, thanks. That's what I thought would happen, just wanted to confirm. So that means any changes (between now and next Tuesday) to the data I use to instantiate the object will not be reflected. So... I'm thinking I need another class, that executes next Tuesday and instantiates the batch object then.

              – PatMcClellan__c
              2 hours ago











            • @PatMcClellan__c Without seeing your code, hard to say, but remember you can also do other stuff in your start method besides just providing a query locator. During the start method might be a perfect time to do any other calculations or queries you need to perform to see if you want to continue or not. You can also use System.abortJob in the start method if you want to cancel your job early (the job Id comes from the BatchableContext object).

              – sfdcfox
              2 hours ago











            • Ah... I was wondering about that. So, instead of providing the entire blast record when I instantiate, I just provide the recordId. Then, in the start method, I do a soql search on it, pull the data at that point in time, or abort if the record no longer exists.

              – PatMcClellan__c
              1 hour ago











            • @PatMcClellan__c Yes, you should always query for the data you're going to work on as late as possible, especially when using asynchronous code that might not be called for a long time.

              – sfdcfox
              1 hour ago











            • I can't find docs on how to pull the jobId while inside the start method. Would it be something like... BC.getJobId() ?

              – PatMcClellan__c
              1 hour ago





















            • OK, thanks. That's what I thought would happen, just wanted to confirm. So that means any changes (between now and next Tuesday) to the data I use to instantiate the object will not be reflected. So... I'm thinking I need another class, that executes next Tuesday and instantiates the batch object then.

              – PatMcClellan__c
              2 hours ago











            • @PatMcClellan__c Without seeing your code, hard to say, but remember you can also do other stuff in your start method besides just providing a query locator. During the start method might be a perfect time to do any other calculations or queries you need to perform to see if you want to continue or not. You can also use System.abortJob in the start method if you want to cancel your job early (the job Id comes from the BatchableContext object).

              – sfdcfox
              2 hours ago











            • Ah... I was wondering about that. So, instead of providing the entire blast record when I instantiate, I just provide the recordId. Then, in the start method, I do a soql search on it, pull the data at that point in time, or abort if the record no longer exists.

              – PatMcClellan__c
              1 hour ago











            • @PatMcClellan__c Yes, you should always query for the data you're going to work on as late as possible, especially when using asynchronous code that might not be called for a long time.

              – sfdcfox
              1 hour ago











            • I can't find docs on how to pull the jobId while inside the start method. Would it be something like... BC.getJobId() ?

              – PatMcClellan__c
              1 hour ago



















            OK, thanks. That's what I thought would happen, just wanted to confirm. So that means any changes (between now and next Tuesday) to the data I use to instantiate the object will not be reflected. So... I'm thinking I need another class, that executes next Tuesday and instantiates the batch object then.

            – PatMcClellan__c
            2 hours ago





            OK, thanks. That's what I thought would happen, just wanted to confirm. So that means any changes (between now and next Tuesday) to the data I use to instantiate the object will not be reflected. So... I'm thinking I need another class, that executes next Tuesday and instantiates the batch object then.

            – PatMcClellan__c
            2 hours ago













            @PatMcClellan__c Without seeing your code, hard to say, but remember you can also do other stuff in your start method besides just providing a query locator. During the start method might be a perfect time to do any other calculations or queries you need to perform to see if you want to continue or not. You can also use System.abortJob in the start method if you want to cancel your job early (the job Id comes from the BatchableContext object).

            – sfdcfox
            2 hours ago





            @PatMcClellan__c Without seeing your code, hard to say, but remember you can also do other stuff in your start method besides just providing a query locator. During the start method might be a perfect time to do any other calculations or queries you need to perform to see if you want to continue or not. You can also use System.abortJob in the start method if you want to cancel your job early (the job Id comes from the BatchableContext object).

            – sfdcfox
            2 hours ago













            Ah... I was wondering about that. So, instead of providing the entire blast record when I instantiate, I just provide the recordId. Then, in the start method, I do a soql search on it, pull the data at that point in time, or abort if the record no longer exists.

            – PatMcClellan__c
            1 hour ago





            Ah... I was wondering about that. So, instead of providing the entire blast record when I instantiate, I just provide the recordId. Then, in the start method, I do a soql search on it, pull the data at that point in time, or abort if the record no longer exists.

            – PatMcClellan__c
            1 hour ago













            @PatMcClellan__c Yes, you should always query for the data you're going to work on as late as possible, especially when using asynchronous code that might not be called for a long time.

            – sfdcfox
            1 hour ago





            @PatMcClellan__c Yes, you should always query for the data you're going to work on as late as possible, especially when using asynchronous code that might not be called for a long time.

            – sfdcfox
            1 hour ago













            I can't find docs on how to pull the jobId while inside the start method. Would it be something like... BC.getJobId() ?

            – PatMcClellan__c
            1 hour ago







            I can't find docs on how to pull the jobId while inside the start method. Would it be something like... BC.getJobId() ?

            – PatMcClellan__c
            1 hour ago















            0














            For the benefit of clarity, I'll share my revised code... the object is actually called Wave, not Blast.



            global class QueueWave implements Database.Batchable<SObject>, Database.Stateful {
            global String waveId;
            global String body;
            global String messageServiceLabel;
            global Integer recipientCount;
            global String emailAddress;
            global String waveName;
            global String userId;

            global QueueWave(String waveId) {
            this.waveId = waveId;
            }


            The constructor does nothing except store the recordId at the time this batch class is scheduled. I'm using try-catch, catching QueryException which aborts the job.



            global Database.QueryLocator start(Database.BatchableContext BC){
            if(Wave__c.SObjectType.getDescribe().isAccessible()){
            try{
            Wave__c wave = [
            SELECT [fields I need, which may have been updated since batch was scheduled]
            FROM Wave__c
            WHERE Id = :this.waveId
            LIMIT 1];

            //set global vars with data from the wave record
            . . .

            String query = // build my query string here
            return Database.getQueryLocator(query);

            }catch(QueryException qe){
            System.debug('QueryException on ' + BC.getJobId() + ' ' + qe);
            System.abortJob(BC.getJobId());
            }
            }
            }





            share|improve this answer




























              0














              For the benefit of clarity, I'll share my revised code... the object is actually called Wave, not Blast.



              global class QueueWave implements Database.Batchable<SObject>, Database.Stateful {
              global String waveId;
              global String body;
              global String messageServiceLabel;
              global Integer recipientCount;
              global String emailAddress;
              global String waveName;
              global String userId;

              global QueueWave(String waveId) {
              this.waveId = waveId;
              }


              The constructor does nothing except store the recordId at the time this batch class is scheduled. I'm using try-catch, catching QueryException which aborts the job.



              global Database.QueryLocator start(Database.BatchableContext BC){
              if(Wave__c.SObjectType.getDescribe().isAccessible()){
              try{
              Wave__c wave = [
              SELECT [fields I need, which may have been updated since batch was scheduled]
              FROM Wave__c
              WHERE Id = :this.waveId
              LIMIT 1];

              //set global vars with data from the wave record
              . . .

              String query = // build my query string here
              return Database.getQueryLocator(query);

              }catch(QueryException qe){
              System.debug('QueryException on ' + BC.getJobId() + ' ' + qe);
              System.abortJob(BC.getJobId());
              }
              }
              }





              share|improve this answer


























                0












                0








                0







                For the benefit of clarity, I'll share my revised code... the object is actually called Wave, not Blast.



                global class QueueWave implements Database.Batchable<SObject>, Database.Stateful {
                global String waveId;
                global String body;
                global String messageServiceLabel;
                global Integer recipientCount;
                global String emailAddress;
                global String waveName;
                global String userId;

                global QueueWave(String waveId) {
                this.waveId = waveId;
                }


                The constructor does nothing except store the recordId at the time this batch class is scheduled. I'm using try-catch, catching QueryException which aborts the job.



                global Database.QueryLocator start(Database.BatchableContext BC){
                if(Wave__c.SObjectType.getDescribe().isAccessible()){
                try{
                Wave__c wave = [
                SELECT [fields I need, which may have been updated since batch was scheduled]
                FROM Wave__c
                WHERE Id = :this.waveId
                LIMIT 1];

                //set global vars with data from the wave record
                . . .

                String query = // build my query string here
                return Database.getQueryLocator(query);

                }catch(QueryException qe){
                System.debug('QueryException on ' + BC.getJobId() + ' ' + qe);
                System.abortJob(BC.getJobId());
                }
                }
                }





                share|improve this answer













                For the benefit of clarity, I'll share my revised code... the object is actually called Wave, not Blast.



                global class QueueWave implements Database.Batchable<SObject>, Database.Stateful {
                global String waveId;
                global String body;
                global String messageServiceLabel;
                global Integer recipientCount;
                global String emailAddress;
                global String waveName;
                global String userId;

                global QueueWave(String waveId) {
                this.waveId = waveId;
                }


                The constructor does nothing except store the recordId at the time this batch class is scheduled. I'm using try-catch, catching QueryException which aborts the job.



                global Database.QueryLocator start(Database.BatchableContext BC){
                if(Wave__c.SObjectType.getDescribe().isAccessible()){
                try{
                Wave__c wave = [
                SELECT [fields I need, which may have been updated since batch was scheduled]
                FROM Wave__c
                WHERE Id = :this.waveId
                LIMIT 1];

                //set global vars with data from the wave record
                . . .

                String query = // build my query string here
                return Database.getQueryLocator(query);

                }catch(QueryException qe){
                System.debug('QueryException on ' + BC.getJobId() + ' ' + qe);
                System.abortJob(BC.getJobId());
                }
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 42 mins ago









                PatMcClellan__cPatMcClellan__c

                791220




                791220






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Salesforce Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f253757%2fwhen-is-a-batch-class-instantiated-when-you-schedule-it%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Reichsarbeitsdienst

                    Statuo de Libereco

                    Tanganjiko