I am using trigger to update the custom field(AccountTerritory__c) in Account based on Territory values assigned in Account. I need to schedule this trigger to run on specified time. Could anyone please provide the solution?
trigger accountTerritoryAssignment on Account (After Insert, After Update) { //List
list<Account> finalList = new list<Account>();
//Variable
boolean flag = false;
if(trigger.isInsert)
{
flag = true;
}
if(trigger.isUpdate)
{
for(Account a:trigger.new)
{
if((trigger.oldMap.get(a.id).BillingCountryCode != trigger.newMap.get(a.id).BillingCountryCode) || (trigger.oldMap.get(a.id).BillingStateCode != trigger.newMap.get(a.id).BillingStateCode))
{
flag = true;
}
}
}
if(flag)
{
if(checkRecursiveAcc.runOnce())
{
for(Account a:trigger.new)
{
//AccountShare List
list<AccountShare> accshareList = new list<AccountShare>();
set<id> accshareSet = new set<id>();
accshareList = [Select Id, UserOrGroupId from AccountShare where (RowCause='TerritoryManual' or RowCause='Territory') and AccountId=: a.id];
system.debug('***accshareList***'+accshareList);
//AccountShare Set
for(integer i=0;i<accshareList.size();i++)
{
accshareSet.add(accshareList[i].UserOrGroupId);
}
// Group List
list<Group> groupList = new list<Group>();
set<id> groupSet= new set<id>();
groupList = [Select Id, RelatedId from Group where Id IN : accshareSet];
system.debug('***groupList***'+groupList);
//Group set
for(integer i=0;i<groupList.size();i++)
{
groupSet.add(groupList[i].RelatedId);
}
//TerritoryName List
list<Territory> territoryList = new list<Territory>();
territoryList = [Select id, name from Territory where Id IN : groupSet];
system.debug('***territoryList***'+territoryList);
Account acc = new Account();
acc.id = a.id;
acc.AccountTerritory__c = null;
for(integer j=0;j<territoryList.size();j++)
{
if(j==0)
{
acc.AccountTerritory__c = territoryList[j].name;
system.debug('***acc.AccountTerritory__c when j=0***'+acc.AccountTerritory__c);
}
else
{
acc.AccountTerritory__c = acc.AccountTerritory__c+','+territoryList[j].name;
system.debug('***acc.AccountTerritory__c when j>0***'+acc.AccountTerritory__c);
}
}
finalList.add(acc);
system.debug('***acc***'+acc);
groupSet.clear();
accshareSet.clear();
}
update finalList;
system.debug('***finelList***'+finalList);
}
}
}