New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Showing posts with label batch apex. Show all posts
Showing posts with label batch apex. Show all posts

Saturday, 10 November 2012

Data Loader batch size

* If the batch size is 50 then if one of the record in those 50 records failed to insert due to error all remaining records in that batch also fail.
* If you try to insert those failed records again with batch size '1' then most of the records will get insert apart from those records which causing problem really.

Wednesday, 17 October 2012

Scheduling Batch Class after 6 minutes whenever a batch finish method executed in salesforce

AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
         TotalJobItems, CreatedBy.Email
         FROM AsyncApexJob WHERE Id =:BC.getJobId()];

* Above syntax is to retrieve information regarding to the jobs.
             Batch_classname bs = new Batch_classname();
             Datetime sysTime = System.now();
             sysTime = sysTime.addminutes(6);
             String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' +
             sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();           
             System.schedule('Update Actual'+sysTime.getTime(),chron_exp, bs);

Tuesday, 16 October 2012

Scheduling batch class for every 5 minutes using system.schedule method in salesforce

Batch_scheduledclassname bs = new Batch_scheduledclassname bs();
String sch = '0 6 * * * ? ';
System.schedule('My Job1', sch, bs);

Note: While writing schedular class don't forget to use datebase.executeBatch method which inturn will run the apex batch class.
* Above 6 means every hour 6th minute.
* If you want to schedule the calss for every 5 minutes then you need paste above code with some changes for 10 times in developer console.
* Changes are:
- instead of 6 replace with 12,18,24..... like that.
- Change the Batch Job name My Job1 to some other name whenever we want to submit new job

Tuesday, 2 October 2012

Using Batch Apex to Change the Account Owners


global class AccountOwnerReassignment implements 
             Database.Batchable<SObject>, Database.Stateful{
    
    User fromUser{get; set;}
    User toUser{get; set;}
    Double failedUpdates{get; set;}
    //Parameter Construcotr
    global AccountOwnerReassignment(User fromUser, User toUser){
        this.fromUser = fromUser;
        this.toUser = toUser;
        failedUpdates = 0;
    }
    
    global Database.queryLocator 
                    start(Database.BatchableContext ctx){
        return Database.getQueryLocator([SELECT id, name, ownerId 
                        FROM Account WHERE ownerId = :fromUser.id]);
    }
    
    global void execute(Database.BatchableContext ctx, List<Sobject> scope){
        List<Account> accs = (List<Account>)scope;
        
        for(Integer i = 0; i < accs.size(); i++){
            accs[i].ownerId = toUser.id;
        }
        
        List<Database.SaveResult> dsrs = Database.update(accs, false);
        for(Database.SaveResult dsr : dsrs){
            if(!dsr.isSuccess()){
                failedUpdates++;
            }
            
        } 
    }
    
    global void finish(Database.BatchableContext ctx){
    
        AsyncApexJob a = [SELECT id, ApexClassId, 
                       JobItemsProcessed, TotalJobItems, 
                       NumberOfErrors, CreatedBy.Email 
                       FROM AsyncApexJob 
                       WHERE id = :ctx.getJobId()];
        
        String emailMessage = 'Your batch job '
             + 'AccountOwnerReassignment '
             + 'has finished.  It executed ' 
             + a.totalJobItems 
             + ' batches.  Of which, ' + a.jobitemsprocessed 
             + ' processed without any exceptions thrown and ' 
             + a.numberOfErrors +
             ' batches threw unhandled exceptions.'
             + '  Of the batches that executed without error, ' 
             + failedUpdates 
             + ' records were not updated successfully.';
        
        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('Batch job completed');
        mail.setPlainTextBody(emailMessage);
        mail.setHtmlBody(emailMessage);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] 
                           { mail });
    }    
}
In Developer Console Paste below code:

User fromUser = [select id,firstname from user where firstname = 'name of the user'];
User toUser = [select id,firstname from user where firstname = 'name of the user'];                 
Database.executeBatch(new AccountOwnerReassignment(fromUser,toUser));
Note: Name of the user means, Goto Managed Users>Click on particuar user> At the top below the User one name will display that name we should give in place of 'name of the user'

Calling Batch Apex from Trigger:
* Goto App Setup> Customize> Account> Triggers

Trigger AccountOwnerReassignment on Account (before insert) {
    List<Account> al = Trigger.new;
    for(Account a:al) {
        User fromUser = [select id,firstname from user where alias = 'alias name'];
        User toUser = [select id,firstname from user where alias = 'alias name'];                 
        try {
            Database.executeBatch(new AccountOwnerReassignment(fromUser,toUser));
        }
        Catch(Exception E) {
        }
    }
}
Note: In case, no rows queried from the SOQL Queries below error will arise.
Error: Invalid Data. Review all error messages below to correct your data.Apex trigger AccountOwnerReassignment caused an unexpected exception, contact your administrator: AccountOwnerReassignment: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.AccountOwnerReassignment: line 4, column 1

Refer:
http://developer.force.com/cookbook/recipe/using-batch-apex-to-reassign-account-owners

Labels