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
Matt GajdaMatt Gajda 

Scheduled Apex Job - CPU Time limit exceeded

Hi all,
 I am getting this error from a scheuled job. I understand that it is taking to much time to process and was hoping someone could take a look at the code for this job and make some reccomendations.

" Scheduler: failed to execute scheduled job: jobId: 707E000003iHjqz, class: common.apex.async.AsyncApexJobObject, reason: Apex CPU time limit exceeded"



Here is the Apex  Code:


global class FindLeadsScheduler implements Schedulable {
    
    global void execute(SchedulableContext ctx) {
        Integer Days = 31; //number of days after Leads becoming inactive
        Date lastDay = Date.Today() - Days;

        
        List<Lead> inactiveLeads = [
            SELECT Id, Project_Site__r.Unprotected_queue_name__c
            FROM Lead
            WHERE isConverted = false AND unprotected__c = false AND Lead.Date_of_last_contact__c < :lastDay
        ];
        
        List<Group> queues = [
            SELECT id, name
            FROM Group
        ];
        Map<String, Id> qMap = new Map<String, Id>();
        for(Group g:queues){
            qMap.put(g.name, g.id);
        }
        for(Lead l:inactiveLeads){
            Id leadQueue = qMap.get(l.Project_Site__r.Unprotected_queue_name__c);
            if(leadQueue != null){
                l.ownerid = leadQueue;
            }
        }
        
        update inactiveLeads;
    }

}



 Any help would be greatly appreciated.

Thanks,

Matt
Amit VaidyaAmit Vaidya
Hi Matt,

Try collecting the Project_Site__r.Unprotected_queue_name__c value in different list and using that to get value in variable "leadQueue".

Thanks,
Amit
Amit VaidyaAmit Vaidya
Also try below some minor updated code:
 
global class FindLeadsScheduler implements Schedulable {
    
    global void execute(SchedulableContext ctx) {
        Integer Days = 31; //number of days after Leads becoming inactive
        Date lastDay = Date.Today() - Days;
		List<Lead> updateLeads = new List<Lead>();
        
        List<Lead> inactiveLeads = [
            SELECT Id, Project_Site__r.Unprotected_queue_name__c
            FROM Lead
            WHERE isConverted = false AND unprotected__c = false AND Lead.Date_of_last_contact__c < :lastDay
        ];
        
        List<Group> queues = [
            SELECT id, name
            FROM Group
        ];
        Map<String, Id> qMap = new Map<String, Id>();
        for(Group g:queues){
            qMap.put(g.name, g.id);
        }
        for(Lead l:inactiveLeads){
            Id leadQueue = qMap.get(l.Project_Site__r.Unprotected_queue_name__c);
            if(leadQueue != null){
                l.ownerid = leadQueue;
				updateLeads.add(l);
            }
        }
        
        update updateLeads;
    }

}