SlideShare a Scribd company logo
8/31/2012




     Using Batch Jobs to Improve
         the User Experience




              Safe Harbor
I've always said to anyone that will listen to me
(which is not very many) that software is an art
form. It attracts artists.
Just look at any software company and the
amount of musicians, artists, carpenters, etc…
working there that create code for a living and
create other things in their down time.
 - Steve Lacey




                                                           1
8/31/2012




 A developer can now employ batch Apex to
 build complex, long-running processes on the
 Force.com platform.




              - Force.com Apex Code Developers Guide




Complex, Long Running tasks

• Pre or Post processing tasks
• Account reassignments
• Price book updates
• Custom or Transactional Objects

Governor Limits are Your Friends …




                                                              2
8/31/2012




            Scenario 1

• 324,476 Accounts

• 142,105 Opportunity records

• 1 NEW record type




       Administrative Use

• Nulling out a field

• Arghhhh!!!!!




                                       3
8/31/2012




      Developer Objects

• Batch Process(es)
• Something to fire it
  – Trigger
  – Schedule
  – VisualForce Page
• Test Class




         Batch Process

• Start – Define the records to
  process
• Execute – “Long, Complex…”
• Finish – Post processing
  – e-Mail status
  – Schedule a repeat job, etc




                                         4
8/31/2012




                                 APEX Code
global class BatchOppLineZero implements Database.Batchable<SObject> {

    global final string query;
    global boolean process_on;

    List<OpportunityLineItemSchedule> schList = new List<OpportunityLineItemSchedule> ();

    private string query1 = 'Select Id, scheduledate, revenue from OpportunityLineItemSchedule';

    global BatchOppLineZero () {

        if (system.Test.isRunningTest()) {
           this.query = query1 + ' where scheduledate >= :chkDate';
        } else {
           this.query = query1 + ' where scheduledate >= :testDate';
        }
    }
*
*




                                 APEX Code
        Start Method

        global Database.queryLocator start(Database.BatchableContext ctx){
           Date myDate = date.today();
           Date chkDate = date.newinstance (mydate.year(),mydate.month(),1).addmonths(-3);
            return Database.getQueryLocator(query);
         }




                                                                                                          5
8/31/2012




                           APEX Code
Execute Method
global void execute(Database.BatchableContext ctx, List<Sobject> scope){
    schList = (List<OpportunityLineItemSchedule>)scope;

       for (OpportunityLineItemSchedule lis:schList) lis.revenue=0;
       update schList;

   }




                             Scenario 1
  n opportunity records need to be updated
  • Record type needs to be changed
  • OwnerId updated
          – Should be the account owner
          – Default for account location if owner is
            inactive
  • Opportunity type should reflect account
    property




                                                                                  6
8/31/2012




                    Execute Method – scenario 1
global void execute(Database.BatchableContext ctx, List<Sobject> scope){
    oppUpdate = (List<Opportunity>)scope;

       List<Account> accList = new List<Account>();
       Set<Id> accId = new set<id>();

       ID recTypeId;
       List<RecordType> recList = new List<RecordType> ([Select Id, Name from RecordType]);
       for (RecordType rec:recList) if (rec.name=='Ad Revenue') recTypeId=rec.id;

       ID pitOwnerID, denOwnerID, laxOwnerID;
       List<User> repList = [Select ID, name, Property__c, IsActive, Sales_id__c from User];
       MAP<string,User> repMap = new MAP<string,User>();
       MAP<Id,User> repActiveMap = new MAP<Id,User>();

       for (User u:repList) {
          repMap.put(u.UserNumber__c,u);
          repActiveMap.put(u.id,u);
          if (u.name == ‘PIT Owner') pitOwnerID=u.id;
          if (u.name == ‘DEN Owner') denOwnerID=u.id;
          if (u.name == ‘LAX Owner') laxOwnerID=u.id;
        }




       for(Opportunity o:oppUpdate) accId.add(o.accountid);

       Map<Id,Account> accMap = new Map<Id,Account> (
           [Select Id, ownerid, property__c from Account where id in: accId]);

       for (Opportunity o:oppUpdate){
        o.description = 'This opportunity is used to track Ordered Ad Revenue';

        Account acc=accMap.get(o.accountid);
        if (acc !=null) {
           o.Opportunity_Type__c = acc.Property__c;

             User rep = repActiveMap.get(acc.ownerid);
             if (rep.IsActive) {
                acc.ownerid = rep.id;
             } else {
                if (acc.property__c == ‘PIT' && pitOwnerId !=null) o.ownerid = pitownerid;
                if (acc.property__c == ‘DEN' && denOwnerId !=null) o.ownerid = denownerid;
                if (acc.property__c == ‘LAX' && laxOwnerId !=null) o.ownerid = laxownerid;
         }

          if (recTypeId !=null) o.RecordTypeId = recTypeId;
        }
      }
      update oppUpdate;
  }




                                                                                                      7
8/31/2012




                                  APEX Code
Finish Method
global void finish(Database.BatchableContext ctx){
    AsyncApexJob a = [SELECT id, ApexClassId, JobItemsProcessed, TotalJobItems,
              NumberOfErrors, CreatedBy.Email
              FROM AsyncApexJob WHERE id = :ctx.getJobId()];

            string emailMessage = 'We executed ' + a.totalJobItems + ' batches.';

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {a.createdBy.email};
            mail.setToAddresses(toAddresses);
            mail.setReplyTo('noreply@salesforce.com');
            mail.setSenderDisplayName('Batch Job Summary');
            mail.setSubject('Opportunity batch update complete');
            mail.setPlainTextBody(emailMessage);
            mail.setHtmlBody(emailMessage);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}




                      Testing your Batch

        @ISTest
        public with sharing class TESTBatchOppLineZero {

            static testMethod void TESTBatchOppLineZero()
            {
              List<Account> actList = new List<Account>();
              *
              *
               Test.startTest();
                 Database.executeBatch(new BatchOppLineZero());
               Test.stopTest();

                 system.assertEquals(…..)
             }

        }




                                                                                             8
8/31/2012




 Governor (and other) Limits

• 5 active jobs
• Can’t call a batch from a batch
• 1M lines of code, 250k daily batches, 10k DML
  statements
• “One at a time”
• Subject to available resources
• Check the docs




           Scheduled Jobs

• After hours processing
• Daily / weekly / monthly jobs
• Asynchronous triggers
• Future jobs




                                                         9
8/31/2012




            Why Not Real Time?

• External processing
     – Third party updates
     – Delivery Status
• Just in time
• Balance resources
• Look at the business and its needs




                       APEX Code

global class BatchStageImportScheduler implements Schedulable {

    global void execute (SchedulableContext ctx)
    {
       BatchStageImport batchImport = new BatchStageImport();
       ID batchprocessid = Database.executeBatch(batchImport);
    }
}




                                                                        10
8/31/2012




                                APEX Code
    global void finish(Database.BatchableContext ctx){
     *
     *
     *
    // Schedule a job for 5 am tomorrow…
     Datetime sysTime = System.now();
     sysTime = sysTime.addDays(1);
     String chron_exp = '' + 0 + ' ' + 0 + ' ' + 5 + ' ' +
                        sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();

     BatchStageImportScheduler BatchSched = new BatchStageImportScheduler();

     // Schedule the next job, and give it the system time so name is unique
      System.schedule('BatchStageImport' + sysTime.getTime(),chron_exp,BatchSched);

     }
}




                          Monitoring Jobs

         • Check status
         • Cancel jobs
         • Error(s)

           Your name -> Setup ->             (Administration Setup)
                  Monitoring ->         Apex Jobs (or) Scheduled Jobs




                                                                                                11
8/31/2012




  Better User Experience

• Asynchronous Triggers
• Improved data quality
  – Enrichment
  – Cleansing
• Don’t make the customer wait




           Next Steps

• Investigate the Business Rules
  – Maybe this is not for you
• Make sure you test

• Don’t make the customer wait




                                         12
8/31/2012




  Questions?

   Mike Melnick

mikem@asktwice.com

   770-329-3664




                           13

More Related Content

What's hot

Spring batch
Spring batchSpring batch
Spring batch
Chandan Kumar Rana
 
Spring batch showCase
Spring batch showCaseSpring batch showCase
Spring batch showCase
taher abdo
 
Spring batch in action
Spring batch in actionSpring batch in action
Spring batch in action
Mohammed Shoaib
 
Performance optimization (balancer optimization)
Performance optimization (balancer optimization)Performance optimization (balancer optimization)
Performance optimization (balancer optimization)
Vitaly Peregudov
 
Before you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution PlansBefore you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution Plans
Timothy Corey
 
Docker, Zabbix and auto-scaling
Docker, Zabbix and auto-scalingDocker, Zabbix and auto-scaling
Docker, Zabbix and auto-scaling
Vitaly Peregudov
 
Flink forward SF 2017: Elizabeth K. Joseph and Ravi Yadav - Flink meet DC/OS ...
Flink forward SF 2017: Elizabeth K. Joseph and Ravi Yadav - Flink meet DC/OS ...Flink forward SF 2017: Elizabeth K. Joseph and Ravi Yadav - Flink meet DC/OS ...
Flink forward SF 2017: Elizabeth K. Joseph and Ravi Yadav - Flink meet DC/OS ...
Flink Forward
 
Fault Tolerance and Job Recovery in Apache Flink @ FlinkForward 2015
Fault Tolerance and Job Recovery in Apache Flink @ FlinkForward 2015Fault Tolerance and Job Recovery in Apache Flink @ FlinkForward 2015
Fault Tolerance and Job Recovery in Apache Flink @ FlinkForward 2015
Till Rohrmann
 
Airflow presentation
Airflow presentationAirflow presentation
Airflow presentation
Ilias Okacha
 
Azkaban
AzkabanAzkaban
Azkaban
wyukawa
 
How Parse Built a Mobile Backend as a Service on AWS (MBL307) | AWS re:Invent...
How Parse Built a Mobile Backend as a Service on AWS (MBL307) | AWS re:Invent...How Parse Built a Mobile Backend as a Service on AWS (MBL307) | AWS re:Invent...
How Parse Built a Mobile Backend as a Service on AWS (MBL307) | AWS re:Invent...
Amazon Web Services
 
Repository performance tuning
Repository performance tuningRepository performance tuning
Repository performance tuning
Jukka Zitting
 
PyCon India 2012: Celery Talk
PyCon India 2012: Celery TalkPyCon India 2012: Celery Talk
PyCon India 2012: Celery Talk
Piyush Kumar
 
Functional? Reactive? Why?
Functional? Reactive? Why?Functional? Reactive? Why?
Functional? Reactive? Why?
Aleksandr Tavgen
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
All Things Open
 
Spring batch
Spring batchSpring batch
Spring batch
Deepak Kumar
 
pgWALSync
pgWALSyncpgWALSync
pgWALSync
Rumman Iftekhar
 
Monitoring infrastructure with prometheus
Monitoring infrastructure with prometheusMonitoring infrastructure with prometheus
Monitoring infrastructure with prometheus
Shahnawaz Saifi
 
Square Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Square Peg Round Hole: Serverless Solutions For Non-Serverless ProblemsSquare Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Square Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Chase Douglas
 
Crash reports pycodeconf
Crash reports pycodeconfCrash reports pycodeconf
Crash reports pycodeconf
lauraxthomson
 

What's hot (20)

Spring batch
Spring batchSpring batch
Spring batch
 
Spring batch showCase
Spring batch showCaseSpring batch showCase
Spring batch showCase
 
Spring batch in action
Spring batch in actionSpring batch in action
Spring batch in action
 
Performance optimization (balancer optimization)
Performance optimization (balancer optimization)Performance optimization (balancer optimization)
Performance optimization (balancer optimization)
 
Before you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution PlansBefore you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution Plans
 
Docker, Zabbix and auto-scaling
Docker, Zabbix and auto-scalingDocker, Zabbix and auto-scaling
Docker, Zabbix and auto-scaling
 
Flink forward SF 2017: Elizabeth K. Joseph and Ravi Yadav - Flink meet DC/OS ...
Flink forward SF 2017: Elizabeth K. Joseph and Ravi Yadav - Flink meet DC/OS ...Flink forward SF 2017: Elizabeth K. Joseph and Ravi Yadav - Flink meet DC/OS ...
Flink forward SF 2017: Elizabeth K. Joseph and Ravi Yadav - Flink meet DC/OS ...
 
Fault Tolerance and Job Recovery in Apache Flink @ FlinkForward 2015
Fault Tolerance and Job Recovery in Apache Flink @ FlinkForward 2015Fault Tolerance and Job Recovery in Apache Flink @ FlinkForward 2015
Fault Tolerance and Job Recovery in Apache Flink @ FlinkForward 2015
 
Airflow presentation
Airflow presentationAirflow presentation
Airflow presentation
 
Azkaban
AzkabanAzkaban
Azkaban
 
How Parse Built a Mobile Backend as a Service on AWS (MBL307) | AWS re:Invent...
How Parse Built a Mobile Backend as a Service on AWS (MBL307) | AWS re:Invent...How Parse Built a Mobile Backend as a Service on AWS (MBL307) | AWS re:Invent...
How Parse Built a Mobile Backend as a Service on AWS (MBL307) | AWS re:Invent...
 
Repository performance tuning
Repository performance tuningRepository performance tuning
Repository performance tuning
 
PyCon India 2012: Celery Talk
PyCon India 2012: Celery TalkPyCon India 2012: Celery Talk
PyCon India 2012: Celery Talk
 
Functional? Reactive? Why?
Functional? Reactive? Why?Functional? Reactive? Why?
Functional? Reactive? Why?
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
Spring batch
Spring batchSpring batch
Spring batch
 
pgWALSync
pgWALSyncpgWALSync
pgWALSync
 
Monitoring infrastructure with prometheus
Monitoring infrastructure with prometheusMonitoring infrastructure with prometheus
Monitoring infrastructure with prometheus
 
Square Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Square Peg Round Hole: Serverless Solutions For Non-Serverless ProblemsSquare Peg Round Hole: Serverless Solutions For Non-Serverless Problems
Square Peg Round Hole: Serverless Solutions For Non-Serverless Problems
 
Crash reports pycodeconf
Crash reports pycodeconfCrash reports pycodeconf
Crash reports pycodeconf
 

Similar to Salesforce Batch processing - Atlanta SFUG

Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
ftz 420
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1
Patrycja Wegrzynowicz
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Introduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalIntroduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-final
M Malai
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizer
Mydbops
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
Sunghyouk Bae
 
Javascript
JavascriptJavascript
Javascript
Sun Technlogies
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
benewu
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
Hitesh Mohapatra
 
Building a Complex, Real-Time Data Management Application
Building a Complex, Real-Time Data Management ApplicationBuilding a Complex, Real-Time Data Management Application
Building a Complex, Real-Time Data Management Application
Jonathan Katz
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Synchronize applications with akeneo/batch
Synchronize applications with akeneo/batchSynchronize applications with akeneo/batch
Synchronize applications with akeneo/batch
gplanchat
 
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Jim Czuprynski
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex
Sujit Kumar
 
Alternate for scheduled apex using flow builder
Alternate for scheduled apex using flow builderAlternate for scheduled apex using flow builder
Alternate for scheduled apex using flow builder
KadharBashaJ
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
Spring Batch in Code - simple DB to DB batch applicaiton
Spring Batch in Code - simple DB to DB batch applicaitonSpring Batch in Code - simple DB to DB batch applicaiton
Spring Batch in Code - simple DB to DB batch applicaiton
tomi vanek
 
Advance Sql Server Store procedure Presentation
Advance Sql Server Store procedure PresentationAdvance Sql Server Store procedure Presentation
Advance Sql Server Store procedure Presentation
Amin Uddin
 
Dapper performance
Dapper performanceDapper performance
Dapper performance
Suresh Loganatha
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
chhaichivon
 

Similar to Salesforce Batch processing - Atlanta SFUG (20)

Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Introduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalIntroduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-final
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizer
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Javascript
JavascriptJavascript
Javascript
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
 
Building a Complex, Real-Time Data Management Application
Building a Complex, Real-Time Data Management ApplicationBuilding a Complex, Real-Time Data Management Application
Building a Complex, Real-Time Data Management Application
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Synchronize applications with akeneo/batch
Synchronize applications with akeneo/batchSynchronize applications with akeneo/batch
Synchronize applications with akeneo/batch
 
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
Autonomous Transaction Processing (ATP): In Heavy Traffic, Why Drive Stick?
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex
 
Alternate for scheduled apex using flow builder
Alternate for scheduled apex using flow builderAlternate for scheduled apex using flow builder
Alternate for scheduled apex using flow builder
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Spring Batch in Code - simple DB to DB batch applicaiton
Spring Batch in Code - simple DB to DB batch applicaitonSpring Batch in Code - simple DB to DB batch applicaiton
Spring Batch in Code - simple DB to DB batch applicaiton
 
Advance Sql Server Store procedure Presentation
Advance Sql Server Store procedure PresentationAdvance Sql Server Store procedure Presentation
Advance Sql Server Store procedure Presentation
 
Dapper performance
Dapper performanceDapper performance
Dapper performance
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 

More from vraopolisetti

Concurforce - Atlanta ASUG Presentation
Concurforce - Atlanta ASUG PresentationConcurforce - Atlanta ASUG Presentation
Concurforce - Atlanta ASUG Presentation
vraopolisetti
 
Salesforce Adoption and Best Practices
Salesforce Adoption and Best PracticesSalesforce Adoption and Best Practices
Salesforce Adoption and Best Practices
vraopolisetti
 
Take Your Sales Pipeline Reporting to the Next Level 05-30-2012
Take Your Sales Pipeline Reporting to the Next Level   05-30-2012Take Your Sales Pipeline Reporting to the Next Level   05-30-2012
Take Your Sales Pipeline Reporting to the Next Level 05-30-2012
vraopolisetti
 
Getting your data into salesforce 5 30-2012
Getting your data into salesforce 5 30-2012Getting your data into salesforce 5 30-2012
Getting your data into salesforce 5 30-2012
vraopolisetti
 
Earning certifications efficiently 5.30.12 atlanta user group
Earning certifications efficiently 5.30.12 atlanta user groupEarning certifications efficiently 5.30.12 atlanta user group
Earning certifications efficiently 5.30.12 atlanta user group
vraopolisetti
 
Atlanta Salesforce UG Meeting 2/23/2011 Symplified
Atlanta Salesforce UG Meeting 2/23/2011 SymplifiedAtlanta Salesforce UG Meeting 2/23/2011 Symplified
Atlanta Salesforce UG Meeting 2/23/2011 Symplified
vraopolisetti
 
Atlanta Salesforce UG 2/23/2012: Release overview deck (spring '12)
Atlanta Salesforce UG 2/23/2012: Release overview deck (spring '12) Atlanta Salesforce UG 2/23/2012: Release overview deck (spring '12)
Atlanta Salesforce UG 2/23/2012: Release overview deck (spring '12)
vraopolisetti
 
Increasing reporting value with statistics
Increasing reporting value with statisticsIncreasing reporting value with statistics
Increasing reporting value with statistics
vraopolisetti
 
Atlanta user group presentation configero 8 nov11
Atlanta user group presentation configero 8 nov11Atlanta user group presentation configero 8 nov11
Atlanta user group presentation configero 8 nov11
vraopolisetti
 
building an app exchange app
building an app exchange appbuilding an app exchange app
building an app exchange app
vraopolisetti
 
Flow presentation
Flow presentationFlow presentation
Flow presentation
vraopolisetti
 
Who Sees What When? Using Dynamic Sharing Rules To Manage Access To Records
Who Sees What When? Using Dynamic Sharing Rules To Manage Access To Records Who Sees What When? Using Dynamic Sharing Rules To Manage Access To Records
Who Sees What When? Using Dynamic Sharing Rules To Manage Access To Records
vraopolisetti
 
Building Robust Applications with Dynamic Visualforce
Building Robust Applications with Dynamic Visualforce Building Robust Applications with Dynamic Visualforce
Building Robust Applications with Dynamic Visualforce
vraopolisetti
 
Build Amazing Website without coding using Salesforce SiteForce
Build Amazing Website without coding using Salesforce SiteForceBuild Amazing Website without coding using Salesforce SiteForce
Build Amazing Website without coding using Salesforce SiteForce
vraopolisetti
 
Configuration tips
Configuration tipsConfiguration tips
Configuration tips
vraopolisetti
 
Apttus atlanta sfdc user group pres feb 2011
Apttus atlanta sfdc user group pres feb 2011Apttus atlanta sfdc user group pres feb 2011
Apttus atlanta sfdc user group pres feb 2011
vraopolisetti
 
Marketing operations and resource management with salesforcecom
Marketing operations and resource management with salesforcecomMarketing operations and resource management with salesforcecom
Marketing operations and resource management with salesforcecom
vraopolisetti
 

More from vraopolisetti (17)

Concurforce - Atlanta ASUG Presentation
Concurforce - Atlanta ASUG PresentationConcurforce - Atlanta ASUG Presentation
Concurforce - Atlanta ASUG Presentation
 
Salesforce Adoption and Best Practices
Salesforce Adoption and Best PracticesSalesforce Adoption and Best Practices
Salesforce Adoption and Best Practices
 
Take Your Sales Pipeline Reporting to the Next Level 05-30-2012
Take Your Sales Pipeline Reporting to the Next Level   05-30-2012Take Your Sales Pipeline Reporting to the Next Level   05-30-2012
Take Your Sales Pipeline Reporting to the Next Level 05-30-2012
 
Getting your data into salesforce 5 30-2012
Getting your data into salesforce 5 30-2012Getting your data into salesforce 5 30-2012
Getting your data into salesforce 5 30-2012
 
Earning certifications efficiently 5.30.12 atlanta user group
Earning certifications efficiently 5.30.12 atlanta user groupEarning certifications efficiently 5.30.12 atlanta user group
Earning certifications efficiently 5.30.12 atlanta user group
 
Atlanta Salesforce UG Meeting 2/23/2011 Symplified
Atlanta Salesforce UG Meeting 2/23/2011 SymplifiedAtlanta Salesforce UG Meeting 2/23/2011 Symplified
Atlanta Salesforce UG Meeting 2/23/2011 Symplified
 
Atlanta Salesforce UG 2/23/2012: Release overview deck (spring '12)
Atlanta Salesforce UG 2/23/2012: Release overview deck (spring '12) Atlanta Salesforce UG 2/23/2012: Release overview deck (spring '12)
Atlanta Salesforce UG 2/23/2012: Release overview deck (spring '12)
 
Increasing reporting value with statistics
Increasing reporting value with statisticsIncreasing reporting value with statistics
Increasing reporting value with statistics
 
Atlanta user group presentation configero 8 nov11
Atlanta user group presentation configero 8 nov11Atlanta user group presentation configero 8 nov11
Atlanta user group presentation configero 8 nov11
 
building an app exchange app
building an app exchange appbuilding an app exchange app
building an app exchange app
 
Flow presentation
Flow presentationFlow presentation
Flow presentation
 
Who Sees What When? Using Dynamic Sharing Rules To Manage Access To Records
Who Sees What When? Using Dynamic Sharing Rules To Manage Access To Records Who Sees What When? Using Dynamic Sharing Rules To Manage Access To Records
Who Sees What When? Using Dynamic Sharing Rules To Manage Access To Records
 
Building Robust Applications with Dynamic Visualforce
Building Robust Applications with Dynamic Visualforce Building Robust Applications with Dynamic Visualforce
Building Robust Applications with Dynamic Visualforce
 
Build Amazing Website without coding using Salesforce SiteForce
Build Amazing Website without coding using Salesforce SiteForceBuild Amazing Website without coding using Salesforce SiteForce
Build Amazing Website without coding using Salesforce SiteForce
 
Configuration tips
Configuration tipsConfiguration tips
Configuration tips
 
Apttus atlanta sfdc user group pres feb 2011
Apttus atlanta sfdc user group pres feb 2011Apttus atlanta sfdc user group pres feb 2011
Apttus atlanta sfdc user group pres feb 2011
 
Marketing operations and resource management with salesforcecom
Marketing operations and resource management with salesforcecomMarketing operations and resource management with salesforcecom
Marketing operations and resource management with salesforcecom
 

Recently uploaded

Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Zilliz
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 

Recently uploaded (20)

Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 

Salesforce Batch processing - Atlanta SFUG

  • 1. 8/31/2012 Using Batch Jobs to Improve the User Experience Safe Harbor I've always said to anyone that will listen to me (which is not very many) that software is an art form. It attracts artists. Just look at any software company and the amount of musicians, artists, carpenters, etc… working there that create code for a living and create other things in their down time. - Steve Lacey 1
  • 2. 8/31/2012 A developer can now employ batch Apex to build complex, long-running processes on the Force.com platform. - Force.com Apex Code Developers Guide Complex, Long Running tasks • Pre or Post processing tasks • Account reassignments • Price book updates • Custom or Transactional Objects Governor Limits are Your Friends … 2
  • 3. 8/31/2012 Scenario 1 • 324,476 Accounts • 142,105 Opportunity records • 1 NEW record type Administrative Use • Nulling out a field • Arghhhh!!!!! 3
  • 4. 8/31/2012 Developer Objects • Batch Process(es) • Something to fire it – Trigger – Schedule – VisualForce Page • Test Class Batch Process • Start – Define the records to process • Execute – “Long, Complex…” • Finish – Post processing – e-Mail status – Schedule a repeat job, etc 4
  • 5. 8/31/2012 APEX Code global class BatchOppLineZero implements Database.Batchable<SObject> { global final string query; global boolean process_on; List<OpportunityLineItemSchedule> schList = new List<OpportunityLineItemSchedule> (); private string query1 = 'Select Id, scheduledate, revenue from OpportunityLineItemSchedule'; global BatchOppLineZero () { if (system.Test.isRunningTest()) { this.query = query1 + ' where scheduledate >= :chkDate'; } else { this.query = query1 + ' where scheduledate >= :testDate'; } } * * APEX Code Start Method global Database.queryLocator start(Database.BatchableContext ctx){ Date myDate = date.today(); Date chkDate = date.newinstance (mydate.year(),mydate.month(),1).addmonths(-3); return Database.getQueryLocator(query); } 5
  • 6. 8/31/2012 APEX Code Execute Method global void execute(Database.BatchableContext ctx, List<Sobject> scope){ schList = (List<OpportunityLineItemSchedule>)scope; for (OpportunityLineItemSchedule lis:schList) lis.revenue=0; update schList; } Scenario 1 n opportunity records need to be updated • Record type needs to be changed • OwnerId updated – Should be the account owner – Default for account location if owner is inactive • Opportunity type should reflect account property 6
  • 7. 8/31/2012 Execute Method – scenario 1 global void execute(Database.BatchableContext ctx, List<Sobject> scope){ oppUpdate = (List<Opportunity>)scope; List<Account> accList = new List<Account>(); Set<Id> accId = new set<id>(); ID recTypeId; List<RecordType> recList = new List<RecordType> ([Select Id, Name from RecordType]); for (RecordType rec:recList) if (rec.name=='Ad Revenue') recTypeId=rec.id; ID pitOwnerID, denOwnerID, laxOwnerID; List<User> repList = [Select ID, name, Property__c, IsActive, Sales_id__c from User]; MAP<string,User> repMap = new MAP<string,User>(); MAP<Id,User> repActiveMap = new MAP<Id,User>(); for (User u:repList) { repMap.put(u.UserNumber__c,u); repActiveMap.put(u.id,u); if (u.name == ‘PIT Owner') pitOwnerID=u.id; if (u.name == ‘DEN Owner') denOwnerID=u.id; if (u.name == ‘LAX Owner') laxOwnerID=u.id; } for(Opportunity o:oppUpdate) accId.add(o.accountid); Map<Id,Account> accMap = new Map<Id,Account> ( [Select Id, ownerid, property__c from Account where id in: accId]); for (Opportunity o:oppUpdate){ o.description = 'This opportunity is used to track Ordered Ad Revenue'; Account acc=accMap.get(o.accountid); if (acc !=null) { o.Opportunity_Type__c = acc.Property__c; User rep = repActiveMap.get(acc.ownerid); if (rep.IsActive) { acc.ownerid = rep.id; } else { if (acc.property__c == ‘PIT' && pitOwnerId !=null) o.ownerid = pitownerid; if (acc.property__c == ‘DEN' && denOwnerId !=null) o.ownerid = denownerid; if (acc.property__c == ‘LAX' && laxOwnerId !=null) o.ownerid = laxownerid; } if (recTypeId !=null) o.RecordTypeId = recTypeId; } } update oppUpdate; } 7
  • 8. 8/31/2012 APEX Code Finish Method global void finish(Database.BatchableContext ctx){ AsyncApexJob a = [SELECT id, ApexClassId, JobItemsProcessed, TotalJobItems, NumberOfErrors, CreatedBy.Email FROM AsyncApexJob WHERE id = :ctx.getJobId()]; string emailMessage = 'We executed ' + a.totalJobItems + ' batches.'; Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {a.createdBy.email}; mail.setToAddresses(toAddresses); mail.setReplyTo('noreply@salesforce.com'); mail.setSenderDisplayName('Batch Job Summary'); mail.setSubject('Opportunity batch update complete'); mail.setPlainTextBody(emailMessage); mail.setHtmlBody(emailMessage); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } } Testing your Batch @ISTest public with sharing class TESTBatchOppLineZero { static testMethod void TESTBatchOppLineZero() { List<Account> actList = new List<Account>(); * * Test.startTest(); Database.executeBatch(new BatchOppLineZero()); Test.stopTest(); system.assertEquals(…..) } } 8
  • 9. 8/31/2012 Governor (and other) Limits • 5 active jobs • Can’t call a batch from a batch • 1M lines of code, 250k daily batches, 10k DML statements • “One at a time” • Subject to available resources • Check the docs Scheduled Jobs • After hours processing • Daily / weekly / monthly jobs • Asynchronous triggers • Future jobs 9
  • 10. 8/31/2012 Why Not Real Time? • External processing – Third party updates – Delivery Status • Just in time • Balance resources • Look at the business and its needs APEX Code global class BatchStageImportScheduler implements Schedulable { global void execute (SchedulableContext ctx) { BatchStageImport batchImport = new BatchStageImport(); ID batchprocessid = Database.executeBatch(batchImport); } } 10
  • 11. 8/31/2012 APEX Code global void finish(Database.BatchableContext ctx){ * * * // Schedule a job for 5 am tomorrow… Datetime sysTime = System.now(); sysTime = sysTime.addDays(1); String chron_exp = '' + 0 + ' ' + 0 + ' ' + 5 + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year(); BatchStageImportScheduler BatchSched = new BatchStageImportScheduler(); // Schedule the next job, and give it the system time so name is unique System.schedule('BatchStageImport' + sysTime.getTime(),chron_exp,BatchSched); } } Monitoring Jobs • Check status • Cancel jobs • Error(s) Your name -> Setup -> (Administration Setup) Monitoring -> Apex Jobs (or) Scheduled Jobs 11
  • 12. 8/31/2012 Better User Experience • Asynchronous Triggers • Improved data quality – Enrichment – Cleansing • Don’t make the customer wait Next Steps • Investigate the Business Rules – Maybe this is not for you • Make sure you test • Don’t make the customer wait 12
  • 13. 8/31/2012 Questions? Mike Melnick mikem@asktwice.com 770-329-3664 13