/** * Sleep at least a second * * Found at: http://boards.developerforce.com/t5/Apex-Code-Development/Best-way-to-delay-until-time-changes-in-a-test/td-p/389619 * */ public static void waitAtLeastASecond() { Integer msPerS = 1000; Datetime start = Datetime.now(); Datetime current = Datetime.now(); // No sleep available so this ugliness Integer counter = 0; while ((current.getTime() / msPerS) == (start.getTime() / msPerS)) { // This code takes about 250ms or more on na3 Long t1 = System.currentTimeMillis(); String bigRandomString = ''; for (Integer i = 0; i < 2000; i++) { bigRandomString += Crypto.getRandomLong(); } for (Integer i = 0; i < 50; i++) { Blob cryptoKey = Crypto.generateAesKey(256); Blob data = Blob.valueOf(bigRandomString); Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data); Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData); } Long t2 = System.currentTimeMillis(); System.debug('>>> delayUntilTimeChanged delayed for ' + (t2 - t1) + ' ms' + ', Count ' + counter + ', ScriptStatements ' + Limits.getScriptStatements() + ' of ' + Limits.getLimitScriptStatements() + ', CpuTime ' + Limits.getCpuTime() + ' of ' + Limits.getLimitCpuTime()); counter++; current = Datetime.now(); } }