This article walks you through automatically refreshing dashboards using apex scheduled job that you can plan to run at specific times.
First, create a new custom setting to store the dashboard IDs that need to be refreshed.
Custom Setting
- Name: Auto Refresh Dashboard
- API Name: Auto_Refresh_Dashboard__c
- A new text field: Dashboard Id
- API Name: Dashboard_Id__c
Then create an apex schedulable batch job that queries the records from the custom setting and refreshes the dashboard matching the dashboard ID. This invokes an API request to refresh the dashboard.
Endpoint: /services/data/v60.0/analytics/dashboards/{Id}
Note: Refresh a dashboard using apex does not automatically reflect on the UI. You have to reload the page to see the refreshed values.
global class AutoRefreshDashboards implements Database.Batchable<sObject>, schedulable, Database.AllowsCallouts {
/*
//Scheduled the job to run every hour
String CRON_EXP = '0 0 * * * ?';
AutoRefreshDashboards cls = new AutoRefreshDashboards();
System.schedule('Auto Refresh Dashboards', CRON_EXP, cls);
*/
String query = 'SELECT Dashboard_Id__c FROM Auto_Refresh_Dashboard__c';
global void execute(SchedulableContext SC) {
database.executebatch(new AutoRefreshDashboards(), 1);
}
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Auto_Refresh_Dashboard__c> scope) {
// execute code
for(Auto_Refresh_Dashboard__c afd : scope){
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
req.setMethod('PUT');
req.setEndpoint(URL.getOrgDomainUrl().toExternalForm() + '/services/data/v60.0/analytics/dashboards/'+afd.Dashboard_Id__c);
Http http = new Http();
HttpResponse res = http.send(req);
system.debug(res.getStatusCode());
system.debug(res.getBody());
}
}
global void finish(Database.BatchableContext BC) {
// finish code
}
}
Keep in mind that it is not good practice to refresh the dashboard more frequently. Because refreshing a dashboard queues several processes that Salesforce runs resulting in up-to-date data. Each source report runs, filters are applied, charts are drawn, and so forth. Salesforce limits the number of times each user can refresh a dashboard to one time per minute. This limit ensures that Salesforce doesn’t queue the same report runs repeatedly, which also lets other important processes run