2013-03-16 15 views
0

我想使用apex在salesforce中實現同步。未來方法未更新字段的值

我的要求是,我必須從未來的方法更新字段。

我在數據庫中有一個名稱爲Counter_ c的字段,我正在調用一個方法將調用3將來的方法。那些未來的方法會嘗試將計數器_c的值增加1.但是字段沒有得到更新。

這裏是我的代碼:

公共無效generateReports(){

ReportHistory__c repHst = new ReportHistory__c(); 
    repHst.Counter__c = 0; 
    insert repHst; 

    generateReport1(repHst.Id); 
    generateReport2(repHst.Id); 
    generateReport3(repHst.Id); 

}

@future 
public static void generateReport1(Id id) { 

List<ReportHistory__c> lstRep = [select Counter__c rom ReportHistory__c where Id = :id]; 
    if(!lstRep.isEmpty()) { 
     ++lstRep[0].Counter__c; 
    } 
    update lstRep; 
} 


@future 
public static void generateReport2(Id id) { 

List<ReportHistory__c> lstRep = [select Counter__c rom ReportHistory__c where Id = :id]; 
    if(!lstRep.isEmpty()) { 
     ++lstRep[0].Counter__c; 
    } 
    update lstRep; 
} 


@future 
public static void generateReport3(Id id) { 

List<ReportHistory__c> lstRep = [select Counter__c rom ReportHistory__c where Id = :id]; 
    if(!lstRep.isEmpty()) { 
     ++lstRep[0].Counter__c; 
    } 
    update lstRep; 
} 

上面的代碼執行後,我想Counter__c應爲3,但它仍然爲0或有時它的1.

請幫助我,如果有任何方式,以便我可以控制futu再調用,這樣,每一個未來的呼叫應當由1

感謝更新Counter__c的價值, 維韋克

回答

1

從你的例子中,它出現在lstRep.isEmpty()支票上未否定。

E.g.在if條件中添加!

@future 
public static void generateReport1(Id id) { 

    List<ReportHistory__c> lstRep = [select Counter__c rom ReportHistory__c where Id = :id]; 
    if(!lstRep.isEmpty()) { 
     lstRep[0].Counter__c++; 
    } 
    update lstRep; 
} 

也有可能您的未來方法正在從隊列中拉出並由不同的應用程序服務器並行處理。如果是這種情況,你有一個併發問題。讀一讀Asynchronous Processing in Force.com。您可以嘗試將FOR UPDATE關鍵字添加到您的SOQL查詢中,但這可能會導致您的某些未來方法超時。