Created
February 25, 2025 05:07
-
-
Save amitastreait/4e04650628b94c130d18b229df28835a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Method to retrieve records created within the last hour | |
| * @param objectName The API name of the Salesforce object to query | |
| * @return List of sObjects created in the last hour | |
| */ | |
| public static List<SObject> getLastHourRecords(String objectName) { | |
| // Calculate the time one hour ago | |
| DateTime oneHourAgo = DateTime.now().addHours(-1); | |
| // Build the dynamic SOQL query | |
| String query = 'SELECT Id, Name, CreatedDate FROM ' + objectName + | |
| ' WHERE CreatedDate >= :oneHourAgo ORDER BY CreatedDate DESC'; | |
| try { | |
| // Execute the query | |
| List<SObject> lastHourRecords = Database.query(query); | |
| System.debug('Found ' + lastHourRecords.size() + ' records created in the last hour'); | |
| return lastHourRecords; | |
| } catch (Exception e) { | |
| System.debug('Error querying ' + objectName + ': ' + e.getMessage()); | |
| throw e; | |
| } | |
| } | |
| // Example usage for Account object | |
| public static void fetchLastHourAccounts() { | |
| List<Account> recentAccounts = (List<Account>)getLastHourRecords('Account'); | |
| // Process the accounts | |
| for(Account acc : recentAccounts) { | |
| System.debug('Recent Account: ' + acc.Name + ' - Created: ' + acc.CreatedDate); | |
| // Do something with each account | |
| } | |
| } | |
| // Alternative approach for a specific object using SOQL directly | |
| public static List<Contact> getLastHourContacts() { | |
| DateTime oneHourAgo = DateTime.now().addHours(-1); | |
| return [SELECT Id, FirstName, LastName, Email, CreatedDate | |
| FROM Contact | |
| WHERE CreatedDate >= :oneHourAgo | |
| ORDER BY CreatedDate DESC]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment