function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Angello Camacho DragoAngello Camacho Drago 

batch class doesn't execute all the batches

I want to send salesforce data to another system, but when I send the data through a batch class when I call the web service in the execute method doesn't execute all the batches, but if in the execute method don't make the callout all the batches execute, I put two counters in the execute method and I am showing in the finish method one for the number of records in the list and the other for the times the execute method is running, and when I execute the batch without make the callouts run all the batches but when execute the batch calling the web service in the execute method don't run all the batches, this is my code:

global class SendFirstDonorData implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful{
    
    public Integer i = 0;
    public Integer j = 0;    
    public Integer action;
    
    global SendFirstDonorData(Integer act){
        action = act;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){                   
         return Database.getQueryLocator('Select npsp__is_Address_Override__c, npsp__Soft_Credit_Last_N_Days__c, npsp__Primary_Contact__c, npsp__Primary_Affiliation__c, npsp__Number_of_Soft_Credits__c, npsp__Number_of_Soft_Credits_Two_Years_Ago__c, npsp__Number_of_Soft_Credits_This_Year__c, npsp__Number_of_Soft_Credits_Last_Year__c, npsp__Number_of_Soft_Credits_Last_N_Days__c, npsp__Last_Soft_Credit_Date__c, npsp__Last_Soft_Credit_Amount__c, npsp__Largest_Soft_Credit_Date__c, npsp__Largest_Soft_Credit_Amount__c, npsp__HHId__c, npsp__First_Soft_Credit_Date__c, npsp__First_Soft_Credit_Amount__c, npsp__Exclude_from_Household_Name__c, npsp__Exclude_from_Household_Informal_Greeting__c, npsp__Exclude_from_Household_Formal_Greeting__c, npsp__Do_Not_Contact__c, npsp__Deceased__c, npsp__Current_Address__c, npsp__Batch__c, npsp__Address_Verification_Status__c,'+ 
                   'npo02__Total_Household_Gifts__c, npo02__TotalOppAmount__c, npo02__TotalMembershipOppAmount__c, npo02__SystemHouseholdProcessor__c, npo02__Soft_Credit_Two_Years_Ago__c, npo02__Soft_Credit_Total__c, npo02__Soft_Credit_This_Year__c, npo02__Soft_Credit_Last_Year__c, npo02__SmallestAmount__c, npo02__OppsClosedThisYear__c, npo02__OppsClosedLastYear__c, npo02__OppsClosedLastNDays__c, npo02__OppsClosed2YearsAgo__c, npo02__OppAmountThisYear__c, npo02__OppAmountThisYearHH__c, npo02__OppAmountLastYear__c, npo02__OppAmountLastYearHH__c, npo02__OppAmountLastNDays__c, npo02__OppAmount2YearsAgo__c, npo02__NumberOfMembershipOpps__c, npo02__NumberOfClosedOpps__c, npo02__Naming_Exclusions__c, npo02__MembershipJoinDate__c, npo02__MembershipEndDate__c, npo02__LastOppAmount__c, npo02__LastMembershipOrigin__c, npo02__LastMembershipLevel__c, '+
                   'npo02__LastMembershipDate__c, npo02__LastMembershipAmount__c, npo02__LastCloseDate__c, npo02__LastCloseDateHH__c, npo02__LargestAmount__c, npo02__Household__c, npo02__Household_Naming_Order__c, npo02__Formula_HouseholdPhone__c, npo02__Formula_HouseholdMailingAddress__c, npo02__FirstCloseDate__c, npo02__Best_Gift_Year__c, npo02__Best_Gift_Year_Total__c, npo02__AverageAmount__c, npe01__Work_Address__c, npe01__WorkPhone__c, npe01__WorkEmail__c, npe01__Type_of_Account__c, npe01__SystemAccountProcessor__c, npe01__Secondary_Address_Type__c, npe01__Private__c, npe01__Primary_Address_Type__c, npe01__Preferred_Email__c, npe01__PreferredPhone__c, npe01__Other_Address__c, npe01__Organization_Type__c, npe01__Home_Address__c, npe01__HomeEmail__c, '+
                   'npe01__AlternateEmail__c, Total_Donado_Hist_rico__c, Total_Donado_2014__c, Total_Donado_2013__c, Total_Donado_2012__c, Total_Donado_2011__c, Total_Donado_2010__c, Total_Donado_2009__c, Total_Donado_2008__c, Total_Donado_2007__c, Total_Donado_2006__c, Total_Donado_2005__c, Total_Donado_2004__c, Total_Donado_2003__c, Total_Donado_2002__c, Total_Donado_2001__c, Title, Tipo_de_registro_CANDIDATO__c, Tiene_nietos__c, Tiene_hijos__c, SystemModstamp, Salutation, ReportsToId, Referente__c, RecordTypeId, PhotoUrl, Phone, Pa_s_Aldeas__c, PSN__c, PSN_Historico__c, PSN_Buscar_Contacto__c, OwnerId, OtherStreet, OtherStateCode, OtherState, OtherPostalCode, OtherPhone, OtherLongitude, OtherLatitude, OtherCountryCode, OtherCountry, OtherCity, OtherAddress, Ocupaci_n__c, No_Recibir_Correo_F_sico__c, Ni_Apadrinado__c, Name, N_mero_de_Documento__c,'+
                   'MobilePhone, Media_2014__c, Media_2013__c, Media_2012__c, Media_2011__c, Media_2010__c, Media_2009__c, Media_2008__c, Media_2007__c, Media_2006__c, Media_2005__c, Media_2004__c, Media_2003__c, Media_2002__c, Media_2001__c, MasterRecordId, MailingStreet, MailingStateCode, MailingState, MailingPostalCode, MailingLongitude, MailingLatitude, MailingCountryCode, MailingCountry, MailingCity, MailingAddress, M_xima_2014__c, M_xima_2013__c, M_xima_2012__c, M_xima_2011__c, M_xima_2010__c, M_xima_2009__c, M_xima_2008__c, M_xima_2007__c, M_xima_2006__c, M_xima_2005__c, M_xima_2004__c, M_xima_2003__c, M_xima_2002__c, M_xima_2001__c, LeadSource, LastViewedDate, LastReferencedDate, LastName, LastModifiedDate, LastModifiedById, LastCUUpdateDate, LastCURequestDate, LastActivityDate, JigsawContactId, Jigsaw, IsEmailBounced, IsDeleted, Id, '+
                   'ID_Externo_Hist_rico__c, HomePhone, Hobbie__c, HasOptedOutOfFax, HasOptedOutOfEmail, Gender__c, FirstName, Fecha_nacimiento_CANDIDATO__c, Fecha_de_ltima_donaci_n_hist_rica__c, Fecha_de_Pr_ximo_Cumplea_os__c, Fecha_de_Captaci_n__c, Fecha_de_Captaci_n_Migraci_n__c, Fecha_de_Activaci_n_Unificada__c, Fecha_de_Activaci_n_Hist_rica__c, Fax, Estado_Civil__c, EmailBouncedReason, EmailBouncedDate, Email, Edad__c, Duplicado__c, DoNotCall, Destino_de_la_Donaci_n__c, Description, Department, Cuotas_pagadas_2009__c, Cuotas_Pagadas_2014__c, Cuotas_Pagadas_2013__c, Cuotas_Pagadas_2012__c, Cuotas_Pagadas_2011__c, Cuotas_Pagadas_2010__c, Cuotas_Pagadas_2008__c, Cuotas_Pagadas_2007__c, Cuotas_Pagadas_2006__c, Cuotas_Pagadas_2005__c, Cuotas_Pagadas_2004__c, Cuotas_Pagadas_2003__c, Cuotas_Pagadas_2002__c, Cuotas_Pagadas_2001__c, Cuotas_No_Pagadas_2014__c,'+ 
                   'Cuotas_No_Pagadas_2013__c, Cuotas_No_Pagadas_2012__c, Cuotas_No_Pagadas_2011__c, Cuotas_No_Pagadas_2010__c, Cuotas_No_Pagadas_2009__c, Cuotas_No_Pagadas_2008__c, Cuotas_No_Pagadas_2007__c, Cuotas_No_Pagadas_2006__c, Cuotas_No_Pagadas_2005__c, Cuotas_No_Pagadas_2004__c, Cuotas_No_Pagadas_2003__c, Cuotas_No_Pagadas_2002__c, Cuotas_No_Pagadas_2001__c, CreatedDate, CreatedById, Cantidad_de_donaciones_No_Pagadas__c, Cantidad_de_Hijos__c, Cantidad_cuotas_No_Pagadas_Hist_ricas__c, Cantidad_Cuotas_Pagadas_Hist_ricas__c, CallCenter_en_Contacto__c, CallCenter_Usuario_Contacto__c, CallCenter_Date_Contacto__c, Birthdate, AssistantPhone, AssistantName, AccountId FROM Contact'); 
    }
    
    global void execute(Database.BatchableContext BC, List<Contact> scope){
        i += scope.size();
        j ++;
        system.debug('#### ' + j);
        system.debug('#### ' + scope.size());
        Map<Id,User> userMap = new Map<Id,User>((List<User>)[SELECT Id, Name FROM User WHERE IsActive = true]);
        
        Map<Id,RecordType> rtMap = new Map<Id,RecordType>((List<RecordType>)[SELECT Id, Name FROM RecordType WHERE SobjectType = 'Contact']);
        JSONGenerator gen = JSON.createGenerator(true);
        gen.writeStartArray();
        for(Contact c : scope){
            gen.writeStartObject();
            gen.writeStringField('Id', c.Id);
            if(action==2){
                if(c.AccountId!=null){
                    gen.writeStringField('Account', c.AccountId);
                }
            }
            if(c.AssistantName!=null && c.AssistantName!=''){
                gen.writeStringField('AssistantName', c.AssistantName);
            }
            if(c.AssistantPhone!=null && c.AssistantPhone!=''){
                gen.writeStringField('AssistantPhone', c.AssistantPhone);
            }
            if(c.Birthdate!=null){
                gen.writeDateField('Birthdate', c.Birthdate);
            }
            if(c.OwnerId!=null){
                gen.writeStringField('Owner', userMap.get(c.OwnerId).Name);
            }
            if(c.RecordTypeId!=null){
                gen.writeStringField('RecordType', rtMap.get(c.RecordTypeId).Name);
            }
            if(c.Jigsaw!=null && c.Jigsaw!=''){
                gen.writeStringField('Jigsaw', c.Jigsaw);
            }
            if(c.Department!=null && c.Department!=''){
                gen.writeStringField('Department', c.Department);
            }
            if(c.Description!=null && c.Description!=''){
                gen.writeStringField('Description', c.Description);
            }
            if(c.DoNotCall!=null){
                gen.writeStringField('DoNotCall', String.valueOf(c.DoNotCall));
            }
            if(c.Email!=null && c.Email!=''){
                gen.writeStringField('Email', c.Email);
            }
            if(c.HasOptedOutOfEmail!=null){
                gen.writeStringField('HasOptedOutOfEmail', String.valueOf(c.HasOptedOutOfEmail));
            }
            if(c.Fax!=null && c.Fax!=''){
                gen.writeStringField('Fax', c.Fax);
            }
            if(c.HasOptedOutOfFax!=null){
                gen.writeStringField('HasOptedOutOfFax', String.valueOf(c.HasOptedOutOfFax));
            }
            if(c.HomePhone!=null && c.HomePhone!=''){
                gen.writeStringField('HomePhone', c.HomePhone);
            }
            if(c.LastCURequestDate!=null){
                gen.writeDateTimeField('LastCURequestDate', c.LastCURequestDate);
            }
            if(c.LastCUUpdateDate!=null){
                gen.writeDateTimeField('LastCUUpdateDate', c.LastCUUpdateDate);
            }
            if(c.LeadSource!=null && c.LeadSource!=''){
                gen.writeStringField('LeadSource', c.LeadSource);
            }
            if(c.MailingStreet!=null && c.MailingStreet!=''){
                gen.writeStringField('MailingStreet', c.MailingStreet);
            }
            if(c.MailingCity!=null && c.MailingCity!=''){
                gen.writeStringField('MailingCity', c.MailingCity);
            }
            if(c.MailingState!=null && c.MailingState!=''){
                gen.writeStringField('MailingState', c.MailingState);
            }
            if(c.MailingPostalCode!=null && c.MailingPostalCode!=''){
                gen.writeStringField('MailingPostalCode', c.MailingPostalCode);
            }
            if(c.MailingCountry!=null && c.MailingCountry!=''){
                gen.writeStringField('MailingCountry', c.MailingCountry);
            }
            if(c.MobilePhone!=null && c.MobilePhone!=''){
                gen.writeStringField('MobilePhone', c.MobilePhone);
            }
            if(c.Salutation!=null && c.Salutation!=''){
                gen.writeStringField('Salutation', c.Salutation);
            }
            if(c.FirstName!=null && c.FirstName!=''){
                gen.writeStringField('FirstName', c.FirstName);
            }
            if(c.LastName!=null && c.LastName!=''){
                gen.writeStringField('LastName', c.LastName);
            }
            if(c.OtherStreet!=null && c.OtherStreet!=''){
                gen.writeStringField('OtherStreet', c.OtherStreet);
            }
            if(c.OtherCity!=null && c.OtherCity!=''){
                gen.writeStringField('OtherCity', c.OtherCity);
            }
            if(c.OtherState!=null && c.OtherState!=''){
                gen.writeStringField('OtherState', c.OtherState);
            }
            if(c.OtherPostalCode!=null && c.OtherPostalCode!=''){
                gen.writeStringField('OtherPostalCode', c.OtherPostalCode);
            }
            if(c.OtherCountry!=null && c.OtherCountry!=''){
                gen.writeStringField('OtherCountry', c.OtherCountry);
            }
            if(c.OtherPhone!=null && c.OtherPhone!=''){
                gen.writeStringField('OtherPhone', c.OtherPhone);
            }
            if(c.Phone!=null && c.Phone!=''){
                gen.writeStringField('Phone', c.Phone);
            }
            if(c.Title!=null && c.Title!=''){
                gen.writeStringField('Title', c.Title);
            }
            if(c.npe01__AlternateEmail__c!=null && c.npe01__AlternateEmail__c!=''){
                gen.writeStringField('AlternateEmail', c.npe01__AlternateEmail__c);
            }
            if(c.CallCenter_Date_Contacto__c!=null){
                gen.writeDateTimeField('CallCenterDateContacto', c.CallCenter_Date_Contacto__c);
            }
            if(c.CallCenter_en_Contacto__c!=null){
                gen.writeStringField('CallCenterenContacto', String.valueOf(c.CallCenter_en_Contacto__c));
            }
            if(c.CallCenter_Usuario_Contacto__c!=null){
                gen.writeStringField('CallCenterUsuarioContacto', userMap.get(c.CallCenter_Usuario_Contacto__c).Name);
            }
            if(c.Fecha_nacimiento_CANDIDATO__c!=null){
                gen.writeDateField('FechaNacimiento', c.Fecha_nacimiento_CANDIDATO__c);
            }
            if(c.Cantidad_Cuotas_No_Pagadas_Hist_ricas__c!=null){
                gen.writeNumberField('CantidadCuotasNoPagadasHistoricas', c.Cantidad_Cuotas_No_Pagadas_Hist_ricas__c);
            }
            if(c.Cantidad_Cuotas_Pagadas_Hist_ricas__c!=null){
                gen.writeNumberField('CantidadCuotasPagadasHistoricas', c.Cantidad_Cuotas_Pagadas_Hist_ricas__c);
            }
            if(c.Cantidad_de_donaciones_No_Pagadas__c!=null){
                gen.writeNumberField('CantidadDonacionesNoPagadas', c.Cantidad_de_donaciones_No_Pagadas__c);
            }
            if(c.Cantidad_de_Hijos__c!=null && c.Cantidad_de_Hijos__c!=''){
                gen.writeStringField('CantidadHijos', c.Cantidad_de_Hijos__c);
            }
            if(c.Destino_de_la_Donaci_n__c!=null && c.Destino_de_la_Donaci_n__c!=''){
                gen.writeStringField('DestinoDonacion', c.Destino_de_la_Donaci_n__c);
            }
            if(c.npsp__Do_Not_Contact__c!=null){
                gen.writeStringField('DoNotContact',  String.valueOf(c.npsp__Do_Not_Contact__c));
            }
            if(c.Duplicado__c!=null){
                gen.writeStringField('Duplicado', String.valueOf(c.Duplicado__c));
            }
            if(c.Edad__c!=null){
                gen.writeNumberField('Edad', c.Edad__c);
            }
            if(c.Estado_Civil__c!=null && c.Estado_Civil__c!=''){
                gen.writeStringField('EstadoCivil', c.Estado_Civil__c);
            }
            if(c.Fecha_de_Activaci_n_Hist_rica__c!=null){
                gen.writeDateField('FechaActivacionHistorica', c.Fecha_de_Activaci_n_Hist_rica__c);
            }
            if(c.Fecha_de_Activaci_n_Unificada__c!=null){
                gen.writeDateField('FechaActivacionUnificada', c.Fecha_de_Activaci_n_Unificada__c);
            }
            if(c.Fecha_de_Captaci_n__c!=null){
                gen.writeDateField('FechaCaptacion', c.Fecha_de_Captaci_n__c);
            }
            if(c.Fecha_de_Pr_ximo_Cumplea_os__c!=null){
                gen.writeDateField('FechaProximoCumpleaños', c.Fecha_de_Pr_ximo_Cumplea_os__c);
            }
            if(c.Fecha_de_ltima_donaci_n_hist_rica__c!=null){
                gen.writeDateField('FechaUltimaDonacionHistorica', c.Fecha_de_ltima_donaci_n_hist_rica__c);
            }
            if(c.Fecha_de_Captaci_n_Migraci_n__c!=null){
                gen.writeDateField('FechaMigracion', c.Fecha_de_Captaci_n_Migraci_n__c);
            }
            if(c.Gender__c!=null && c.Gender__c!=''){
                gen.writeStringField('Gender', c.Gender__c);
            }
            if(c.Hobbie__c!=null && c.Hobbie__c!=''){
                gen.writeStringField('Hobbie', c.Hobbie__c);
            }
            if(c.ID_Externo_Hist_rico__c!=null && c.ID_Externo_Hist_rico__c!=''){
                gen.writeStringField('IdExternoHistorico', c.ID_Externo_Hist_rico__c);
            }              
            gen.writeEndObject();
        }
        gen.writeEndArray();
        
        String method = 'POST';
        
        if(action==2){
            //action = '?Id=' + c.Id;
            method = 'PUT';
        }
        final PageReference theUrl = new PageReference('http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
    
        HttpRequest request = new HttpRequest();
        request.setEndpoint(theUrl.getUrl());
        request.setHeader('Content-Type', 'application/json');
        request.setMethod(method);
        request.setTimeout(120000);
        request.setBody(gen.getAsString());        
        
        HttpResponse response = (new Http()).send(request);
        system.debug('#### getBody' + response.getBody());
    }
    
    global void finish(Database.BatchableContext BC) {
        system.debug('#### list size: ' + i);
        system.debug('#### number of executions: ' + j);
    }
}