I have been reading about CPU time limit, but can't seem to find a solution to my scheduler. Can someone help me? How can I improve this? It works in Sandbox, but not in Production.
Error message:
Scheduler: failed to execute scheduled job: jobId: 7071L00007omAoo, class: common.apex.async.AsyncApexJobObject, reason: Apex CPU time limit exceeded
Apex Class:
global class UpdateAssetsScheduler implements Schedulable {
global void execute(SchedulableContext SC) {
List<Order> orders = [Select Id,Name,AccountId
from Order
where Cancel_All_Accounts__c = true
and (Type = 'A Cancellation' OR Type= 'B Cancellation')
and Approved_Cancel_All_Assets__c = true
and Billing_Start_Date__c =: System.Today()
];
List<String> accountIds = new List<String>();
for(Order o: orders){
if(o.AccountId != null){
accountIds.add(o.AccountId);
}
}
List<Account> accounts = [Select Id,Name,Account_Status__c,(select Id,Name,Status from Assets)
from Account
where Id =: accountIds
];
List<Asset> assets = new List<Asset>();
for(Account acc : accounts){
List<Asset> child_assets = acc.Assets;
for(Asset a : child_assets){
a.Status = 'Not Active';
assets.add(a);
}
acc.Account_Status__c = 'Non-Active';
}
update assets;
update accounts;
}
}
O(n)
complexity, notO(n^2)
complexity.