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
Art Smorodin 7Art Smorodin 7 

Getting "Apex CPU time limit exceeded" error.Can anyone help?

Hello everyone, 

I am new to VisualForce but have some experiense doing Triggers and Classes. Trying to devlop a VF page which will show Contacts and Leads under a single view, frouped by Stage ( Stage__c is a common field on both Objects). Tbale should also have some data related to Tasks ( if a Contact has 5 overdue tasks, table shoud show that count). 

I have VF page, Controlled and a class partially developped.  As I add ned fields and calculations I test the page. It was working fine but now I see that "Apex CPU time limit exceeded " error. 
Can you guys look at my code and suggest some modifications. Please be advised that my code is a bit of a mess, since I was taking parts of codes from all over the place and tried to fmodify it to meet my needs. 

VF Page:
<apex:page controller="DisplaySectionsController" sidebar="false" readOnly="true">  
  <apex:sectionHeader title="My Sample Display Page" subtitle="Group by States" 
    description="This page shows how you can dynamically group results by field value."/>
 <apex:pageBlock title="My Tasks">
  	<table  border="1">
        <td width="50%"></td>
        <td id="pastdue">New contact requests</td>
        <td><apex:outputText value="" id="theValue"/></td>
        <td id="pastdue">Past due</td>
        <td><apex:outputLink value="/00O36000006wJ0w" id="theLink"><apex:outputText value="{!pastDue}" /></apex:outputLink></td>
        <td id="bold">Due today</td>
        <td><apex:outputText value="{!dueTod}"/></td>
        <td id="bold">Due tomorrow</td>
        <td><apex:outputText value="{!dueTmr}"/></td>
        <td>Due next 7 days</td>
        <td><apex:outputText value="{!duen7d}"/></td> 
        <td>Other scheduled</td>
  <apex:repeat value="{!states}" var="state">

    <apex:pageBlock title="People is Stage: {!state}" > 
     	  <table border = "1" width = "100%">
     	  	<td>Overdue Tasks</td>
     	  	<td>Scheduled Tasks</td>
     	  	<td>Most recent prospect Activity (days)</td>
     	  	<td>Most recent interaction (days)</td>
     	  	<td>Next interaction (days)</td>
     	  	<td>Prospect Rating</td>
     	  	<td>Other key contacts</td>
     	  	<td>Other non-key contacts</td>
     	  	<td>Contact description</td>
     	  	<td>Most recent expression</td>
     	  	<td>Most recent interaction</td>
     	  	<td>Next Task</td>
          <apex:repeat value="{!RowList}" var="item"><apex:outputPanel rendered="{!IF(state=item.Stage,true,false)}">
  		  <tr align ="center">
     	  	<td><apex:outputText value="{!item.stars}" escape="false"/></td>




public with sharing class DisplaySectionsController {
	public List<Contact> contacts {get;set;}  
  	public List<Lead> leads {get;set;}  
  	public String[] states {get;set;}
  	List<Task> myTasks2;
  	Map<String, List<Id>> listMyTasks = new Map<String, List<Id>>();
  	private  Integer pastDue; 
	private  Integer dueTod ;
	private  Integer dueTmr;
	private  Integer duen7d;
	//public List<TableRow> RowList {get; set;}
	TskQueryClass TQC = new TskQueryClass(); 
	Public class TableRow{
	public String Name {get; set;}
	public Integer overTsk {get; set;}
	public Integer schedTsk {get; set;}
	public Integer MRPAd {get; set;}
	public Integer MRIntd {get; set;}
	public Integer NxtIntd {get; set;}
	public Integer Rating {get; set;}
	public String conDesc {get; set;}
	public String MRExp {get; set;}
	public String MRint {get; set;}
	public String NxtTsk {get; set;}
	public String Stage {get; set;}
	public String stars {get; set;}
  public  DisplaySectionsController() {

    // for demo purposes limit the states  
    contacts = [Select ID, Name, Stage__c, Account.Name,scoring_prospect_level_stars__c From Contact 
      Where Stage__c IN ('SAL', 'MQL','Buyer', 'Relevant', 'Connected','Qualifying','Actionable Response','Response','Prospecting','Target','Name') AND OwnerId = :userinfo.getuserId() AND CreatedDate >= 2016-01-01T00:00:00.000Z];
	leads = [Select ID, Name, Stage__c, Company From Lead 
      Where Stage__c IN ('SAL', 'MQL','Buyer', 'Relevant', 'Connected','Qualifying','Actionable Response','Response','Prospecting','Target','Name') AND OwnerId = :userinfo.getuserId() AND CreatedDate >= 2016-01-01T00:00:00.000Z];
    // dynamically create set of unique states from query
    Set<String> stateSet = new Set<String>();
    String[] stateSet2 = new String[]{'SAL', 'MQL','Buyer', 'Relevant', 'Connected','Qualifying','Actionable Response','Response','Prospecting','Target','Name'} ;
    for (Contact a : contacts)
	for (Lead l : leads)
    // convert the set into a string array  
    states = new String[stateSet.size()];
    Integer i = 0;
    for (String state : stateSet) { 
      states[i] = state;
	myTasks2 = TQC.returnmyTasks();
		for(Task a : myTasks2){
    		List<String> temp = listMyTasks.get(a.xTask_Status__c);
    		if(temp == null) {
        		listMyTasks.put(a.xTask_Status__c, new List<Id>{a.Id});
    		else {
  }//end DisplaySectionsController()
  public Integer getpastDue(){
    	List<id> temp = listMyTasks.get('Pastdue');
        if (temp != NULL) pastDue = temp.size();
        else pastDue = 0;
        return pastDue;
    public Integer getdueTod(){
    	List<id> temp = listMyTasks.get('DueToday');
        if (temp != NULL) dueTod = temp.size();
        else dueTod = 0;
        return dueTod;
    public Integer getdueTmr(){
    	List<id> temp = listMyTasks.get('DueTmr');
        if (temp != NULL) dueTmr = temp.size();
        else dueTmr  = 0;
        return dueTmr;
    public Integer getduen7d(){
    	List<id> temp = listMyTasks.get('Scheduled');
        if (temp != NULL)  duen7d = temp.size();
        else duen7d  = 0;
        return duen7d;
	    public List<TableRow> getRowList(){
    	String MRPAtype = VFReporting_page__c.getInstance().Most_recent_prospect_activity_type__c;
    	String MRPAsub = VFReporting_page__c.getInstance().Most_recent_prospect_activity_subject__c;
    	Date startDate =;
        List<Task> MRPA;
        Integer MRPAdsice;
		List<TableRow> RowList = new List<TableRow>();
		TableRow tr;
		Integer i = 0;
		String[] val =  new String[]{'Name','Target','Prospecting','Response', 'Actionable Response','Qualifying','Connected', 'Relevant', 'Buyer', 'MQL', 'SAL', 'SQL', 'Customer'};
		Map<Id, Task> testMap = new Map<Id, Task>([Select Id, whoId, xTask_Status__c from Task where OwnerId = :userinfo.getuserId() AND Status IN ('Not Started', 'In Progress') ]); 
			for (Contact con :contacts){
				tr = new TableRow();
				tr.Name = con.Account.Name + ': '+ con.Name;
				tr.Stage = con.Stage__c;
				tr.stars = con.scoring_prospect_level_stars__c;
				tr.overTsk =, testMap.values());
				tr.schedTsk =, testMap.values());
			for (Lead led : leads){
				tr = new TableRow();
				tr.Name =led.Company + ': '+ led.Name;
				tr.Stage = led.Stage__c; 
				tr.overTsk =, testMap.values());
				tr.schedTsk =, testMap.values());
		return RowList;

public with sharing class TskQueryClass {
    Public Static List<Task> myTaskList= New List<Task>();
    Public Static Integer t6, t7;

    public List<Task> returnmyTasks(){
    	myTaskList =[Select id, ActivityDate, WhoId,xTask_Status__c  from Task where OwnerId = :userinfo.getuserId() AND Status IN ('Not Started', 'In Progress') AND Subject IN ('New lead', 'Contact Request')];
    	return myTaskList;
    public Integer abc(id ID, List<Task> Tazk){
    	List<id> op = new List<Id>();
    	for (Task t : Tazk){
    		if(t.whoId == ID && t.xTask_Status__c == 'Pastdue') op.add(t.whoId);
    	return t6;
    public Integer bbc(id ID, List<Task> Tazk){
    	List<id> op2 = new List<Id>();
    	for (Task t : Tazk){
    		if(t.whoId == ID && t.xTask_Status__c == 'Scheduled') op2.add(t.whoId);
    	return t7;

Thank you in advance!