1

I have trigger which generates random String whenever a record is created. whenever i try to create a record (On clicking the save button), the following error is popping System.LimitException: Apex CPU time limit exceeded. The code that i am using within the trigger is method that i am using within the trigger is take from a similar post right here in StackExchange.

    trigger ITAssetTrigger on IT_Asset_Management__c (before insert) {

    for(IT_Asset_Management__c asset : Trigger.new){
        asset.Asset_Id__c = generateRandomString(Datetime.now().getTime().intValue());    
    }

    public static String generateRandomString(Integer len) {
    final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    String randStr = '';
    while (randStr.length() < len) {
       Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
       randStr += chars.substring(idx, idx+1);
    }
    return randStr; 
   }
}

Can you Help me in updating the code so that i wont get this issue again

Thank you.

2
  • I went into more precise detail on various algorithms and their performance in this question: salesforce.stackexchange.com/questions/43823
    – sfdcfox
    Commented Dec 20, 2016 at 18:34
  • I first tried this code. But it is giving me the following error. System.LimitException: Apex CPU time limit exceeded Commented Dec 20, 2016 at 18:49

3 Answers 3

3

I just realized your problem; you're asking the system to generate a random string that is several million characters long (the parameter to the function being the current time in milliseconds, truncated to a 32-bit number). Instead, you should pass the value 6 instead:

for(IT_Asset_Management__c asset : Trigger.new){
    asset.Asset_Id__c = generateRandomString(6);
}
1
  • Awesome. It Worked> thank you everyone for helping me out with this issue. Commented Dec 20, 2016 at 19:40
0

This code was once posted somewhere here in SE and I found it very useful.. try this..

//To generate use: GenerateRandomUniqueNumber.NewUniqueNumber();

global class GenerateRandomUniqueNumber {

    private static String kHexChars = '0123456789abcdef';

    global static String NewUniqueNumber() {

        String returnValue = '';
        Integer nextByte = 0;

        for (Integer i=0; i<16; i++) {

            if (i==4 || i==6 || i==8 || i==10) 
                returnValue += '-';

            nextByte = (Math.round(Math.random() * 255)-128) & 255;

            if (i==6) {
                nextByte = nextByte & 15;
                nextByte = nextByte | (4 << 4);
            }

            if (i==8) {
                nextByte = nextByte & 63;
                nextByte = nextByte | 128;
            }

            returnValue += getCharAtIndex(kHexChars, nextByte >> 4);
            returnValue += getCharAtIndex(kHexChars, nextByte & 15);
        }

        return returnValue;
    }

    global static String getCharAtIndex(String str, Integer index) {

        if (str == null) return null;

        if (str.length() <= 0) return str;    

        if (index == str.length()) return null;    

        return str.substring(index, index+1);
    }
}
1
  • This is generating a value like this. nullnullnullnullnullnullnullnull-nullnullnullnull-nullnullnullnull-nullnullnullnull-nullnullnullnullnullnullnullnullnullnullnullnull. This is weird Commented Dec 20, 2016 at 18:12
0

You can use this to generate random string

String sRandom = String.ValueOf(Integer.valueOf(math.rint(math.random()*1000000)));

Like this:

for(IT_Asset_Management__c asset : Trigger.new){
        asset.Asset_Id__c = String.ValueOf(Integer.valueOf(math.rint(math.random()*1000000)));    
    }

Update

Also, you can leverage sessionId string and generate alpha-numeric String

    for(IT_Asset_Management__c asset : Trigger.new){
                asset.Asset_Id__c = String.ValueOf(Integer.valueOf(math.rint(math.random()*1000000))) + 
UserInfo.getSessionId().mid(15+Integer.valueOf(math.rint(math.random()*10)),9) ;    
            }
4
  • You mean use this line instead of String randStr = ' '; Commented Dec 20, 2016 at 16:23
  • updated my answer Commented Dec 20, 2016 at 16:33
  • It worked. It generated 6 digit number. Is there a way to add alphabets in between these numbers and generate a alpha numeric string. Commented Dec 20, 2016 at 17:10
  • updated with alpha numeric string Commented Dec 20, 2016 at 18:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .