salesforce - 为什么 Apex Schedulable 类中的全局 Map 不包含任何值?

标签 salesforce

我试图在可批处理类的 finish() 方法中使用全局 Map 变量,但它的行为很奇怪,我确信我做错了什么,但不知道哪里错了。 在下面的简化代码中,第一条调试消息按预期输出 map 的实际大小。但是,finish() 方法中的调试消息输出 0,作为同一映射的大小。看起来 map 在途中的某个地方被重新实例化,但我不确定在哪里。

 global class MySchedulableClass implements Database.Batchable<sObject> {


    global map<string,string> StringStringMap;
    global string query;


    global MySchedulableClass(){    

      if (query == null)
         query = 'Select id, name From Contact LIMIT 20';  
      if (StringStringMap == null){
            StringStringMap = new map<string,string>();
        }
     }

    global Database.QueryLocator start(Database.BatchableContext BC){

        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC,List<sObject> scope){
        for(Sobject s: scope) {
            con = (Contact) s;          
            StringStringMap.put(s.id, s.name);                                                                  
        }
        system.debug('Map size:' + StringStringMap.size());

    }

    global void finish(Database.BatchableContext BC){       
          system.debug('Map size:' + StringStringMap.size());
    }
}

最佳答案

如果您想在批处理运行期间保留信息,请查看 Database.Stateful。请参阅Using State in Batch Apex 。它涵盖了全局变量不持久的原因。

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter is considered five transactions of 200 records each.

If you specify Database.Stateful in the class definition, you can maintain state across these transactions.

关于salesforce - 为什么 Apex Schedulable 类中的全局 Map 不包含任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070332/

相关文章:

crm - 是否可以使用 google 应用程序 (google.com/a) 将应用程序直接构建到 gmail 中?

salesforce - Twilio MMS 发送本地文件

javascript - 如何在 Salesforce 上使用 JSZip 从 Google Drive 下载多个文件作为 .zip

c# - 是否可以在使用 SalesForce Soap API 插入之前向自定义对象添加附件?

salesforce - 在 salesforce.com 中测试 Rest Web 服务

python-3.x - 如何通过 OAuth 通过 CData ODBC 驱动程序对 Salesforce 进行身份验证?

api - Salesforce EMP 连接器,一段时间后停止接收通知

salesforce - 什么是 salesforce 中的应用程序

salesforce - 我在 Trailhead 挑战中的代码有什么问题 开发人员初学者 > Apex 触发器 > 批量 Apex 触发器

c# - SalesForce - 使用 .Net SDK 或 Api 获取对象的所有字段