You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Async Apex执行限额达70%时发送告警通知的需求

How to Alert When Async Apex Daily Usage Hits 70% of Org Limit

Got it, let's break down exactly how to set up an alert when your Salesforce org's daily Async Apex execution limit hits 70% of its total. This is a common requirement to avoid hitting hard limits and disrupting processes, so here's a practical, step-by-step solution:

Step 1: Understand Where to Pull Metrics

First, you need two key pieces of data:

  • Org's daily Async Apex limit: Stored in the Organization object's DailyAsyncApexExecutionsLimit field (this is dynamic, so it’ll update automatically if your org’s limit changes).
  • Current day's usage: Count of completed/failed/aborted AsyncApexJob records created today—these represent executions that count against the daily limit.

Step 2: Build a Scheduled Apex Monitor Class

Create an Apex class that runs on a schedule, checks usage vs. limit, and triggers an alert when the 70% threshold is crossed. Here's a complete, tested example:

global class AsyncApexLimitMonitor implements Schedulable {
    global void execute(SchedulableContext sc) {
        // Fetch the org's daily Async Apex limit
        Organization orgDetails = [SELECT DailyAsyncApexExecutionsLimit FROM Organization LIMIT 1];
        Integer dailyLimit = orgDetails.DailyAsyncApexExecutionsLimit;
        
        // Calculate the 70% threshold (rounded to nearest whole number)
        Integer threshold = Math.round(dailyLimit * 0.7);
        
        // Count today's qualifying Async Apex executions
        Integer currentUsage = [SELECT COUNT() FROM AsyncApexJob 
                               WHERE CreatedDate = TODAY 
                               AND Status IN ('Completed', 'Failed', 'Aborted')];
        
        // Trigger alert if we've hit or exceeded the threshold
        if (currentUsage >= threshold) {
            sendAlertNotification(dailyLimit, currentUsage);
        }
    }
    
    private void sendAlertNotification(Integer dailyLimit, Integer currentUsage) {
        // Set up email alert (replace recipients with your team's emails)
        Messaging.SingleEmailMessage alertMail = new Messaging.SingleEmailMessage();
        alertMail.setToAddresses(new String[] {'dev-team@yourcompany.com', 'ops@yourcompany.com'});
        alertMail.setSubject('🚨 Salesforce Async Apex Limit Alert: 70% Threshold Hit');
        
        // Build a clear, actionable email body
        alertMail.setPlainTextBody(
            'Important Alert: Your Salesforce org has reached 70% of its daily Async Apex execution limit.\n\n' +
            'Details:\n' +
            '- Daily Limit: ' + dailyLimit + ' executions\n' +
            '- Current Usage: ' + currentUsage + ' executions\n' +
            '- Percentage Used: ' + Math.round((currentUsage.doubleValue()/dailyLimit)*100) + '%\n\n' +
            'Next Steps:\n' +
            '1. Review pending Async Apex jobs to prioritize critical ones\n' +
            '2. Reschedule non-essential jobs for tomorrow if possible\n' +
            '3. Check for any runaway batch jobs that might be consuming excess limits'
        );
        
        // Send the email (wrap in try/catch to handle failures gracefully)
        try {
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {alertMail});
        } catch (Exception e) {
            System.debug('Failed to send alert email: ' + e.getMessage());
        }
    }
}

Step 3: Schedule the Monitor

You need to schedule this class to run at regular intervals to catch the threshold hit in time. Here are two ways to do it:

Option 1: Via Salesforce Setup

  1. Go to Setup > Apex Classes
  2. Click Schedule Apex
  3. Name the job (e.g., "Async Apex Limit Monitor"), select your AsyncApexLimitMonitor class, and set a cron schedule. For most orgs, running every 2 hours during business hours works well.

Option 2: Via Anonymous Apex

Run this code in the Developer Console to schedule it programmatically (adjust the cron expression to fit your needs):

// Cron expression: Run every 2 hours from 8 AM to 6 PM, Monday-Friday
String cronSchedule = '0 0 8-18/2 ? * MON-FRI';
System.schedule('Async Apex Limit Monitor', cronSchedule, new AsyncApexLimitMonitor());

Key Notes & Enhancements

  • Permissions: Ensure the user running the scheduled class has these permissions: View Setup and Configuration (to read the Organization object), Send Email, and access to AsyncApexJob records.
  • Notification Channels: If you prefer Slack, Chatter, or another tool instead of email, replace the sendAlertNotification method with integration code for that platform.
  • Frequency: If your org uses Async Apex heavily, consider running the monitor hourly instead of every 2 hours to get alerts sooner.
  • Avoid Duplicate Alerts: To prevent sending multiple alerts in one day once the threshold is hit, add a check (e.g., a custom setting or record) to track if an alert was already sent today.

内容的提问来源于stack exchange,提问作者Harjeet Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:42:18