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
Aldrino Rodrigues 3Aldrino Rodrigues 3 

Scheduled Apex Trigger - to Auto update Custom Field Values if Conditions are met.

Hi,

Please can someone help with with an Apex scheduled trigger or guide me in the right direction.

I have the below custom fields in Salesforce :
Date field >> 'Renewal date'
Pick list  >>  'Account Type' 
Pick list  >>  'Contract Type' 
Text Field >> 'Product 1 Delivered'
Text Field >> 'Product 2 Delviered' 

The Trigger is to run daily

I've tried to explain the query logic as best as i can below.
 
IF 
     Renewal date = Today
              AND
      Contact Type = "Auto-Renew"
             AND
( Account Type = 'Active Client' - OR - 'On-Hold Client' )



THEN,
           UPDATE 'Product 1 Delivered' = 0,
           UPDATE 'Product 1 Delivered' = 0,
           UPDATE Renewal date = Renewal date + 365
. i.e next year



I'd also love if there was a way to send out an email alert or chatter post; however this is secondary.

I hope this make sense.....

I dont know enough APEX to do this yet. Any help will be highly appriciated.

Thank you
badibadi
I would suggest using Scheduled Batch to do that.

Following is the code, 

Batch Class:
global class autoRenewBatch implements Database.Batchable<sobject>, Datbase.Stateful{
    String query;
    global Integer totalRenewals;
    global Integer success;
    global Integer failed;
    
    global autoRenewBatch(){
        totalRenewals=0;
        success=0;
        failed=0;
		Date today= System.today();
        query='SELECT Id, RenewalDate__c, AccountType__c, ContractType__c, Product1Delivered__c, Product2Delivered__c FROM Client__c WHERE RenewalDate__c = :today AND ContactType__c = \'Auto-Renew\' AND (AccountType__c = \'Active Client\' OR AccountType__c =\'On-Hold Client\')';
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Client__c> clients){
        for(Client__c c :clients){
            c.Product1Delivered__c=0;
            c.Product2Delivered__c=0;
            c.RenewalDate__c = c.RenewalDate__c.addDays(365);
        }
        Database.SaveResult[] deleteResultArray = Database.update(clients);
   		for (Database.DeleteResult result : deleteResultArray) {
            totalRenewals+= 1;
   			if ( result.isSuccess() ) success += 1;
   			else failed += 1;
   		}
    }
    
    global void finish(Database.BatchableContext BC){
        String msgBody='Batch to autorenew is complete \n Total of '+success+' were successully renewed and '+failed+' failed to auto-renew';
        // Initialize a single email message.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        string [] toaddress= New string[]{'uremail@company.com'};
        mail.setToAddresses(toaddress);
        mail.setSaveAsActivity(false);
        mail.setSubject('Auto - Renewals - Batch Job Complete');
        mail.setPlainTextBody(msgBody);
        // Send the email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

Scheduled class:
 
global class autoRenewScheduler implements Schedulable{
    public static string con_exp= System.Label.AutoRenewSchedule; //or 0 0 6 ? * * // 6 am every day
    global void execute(SchedulableContext sc){
        ID BatchId= Database.executeBatch(new autoRenewBatch(), 200);
    }
    
    public static Id SchedulerMethod(String name){
    	Id jobId= System.Schedule(name, con_exp, new autoRenewScheduler() );
    	return jobId;
    }
}

Currently, the Batch class has dummy field names so you will have to change those with your actual field and object names.
Scheduled Class: I prefer storing the schedule(when to run the batch job) in  a custom label so we can change the schedule without requiring us to change the code. so will need to create a new custom label with  Name: AutoRenewSchedule and Value: 0 0 6 ? * *  it is set to run at 6 am everyday. 

then execute in Developer Console >> execute anonymus 

autoRenewScheduler.SchedulerMethod('Daily Auto-Renewal');

Hope this helps, Good Luck!