当前位置:网站首页>Salesforce Future method in salesforce – @future
Salesforce Future method in salesforce – @future
2022-06-24 00:04:00 【repick】
future Method is used to run a process in a separate thread when system resources are available , We can future Method is used for any operation that we want to run asynchronously in its own thread .
1. Generally used for the following 2 Kinds of scenes :
·external Web services callout
·Trigger in DML After implementation , Again CallOut operation .
2. Method constitution
· Specify before the method @future label
· When necessary static Method and returns a value void
· Arguments must be basic data types or collections of basic data types
· Arguments cannot use standard Object Type or sObject type
· Arguments are generally used List record IDs To transfer data
Composition example :
global class SomeClass {
@future
public static void someFutureMethod(List<Id> recordIds) {
List<Account> accounts = [Select Id, Name from Account Where Id IN :recordIds];
// process account records to do awesome stuff
}
} 3. Be careful :
· Arguments cannot use standard Object Type or sObject Type of reason ,future Time to wait during method execution , In the process Object There is a possibility that the value in , Easy to cause bad effects .
·future Method does not guarantee execution order ,2 individual future Methods are easy to execute at the same time , If you update a piece of data at the same time , It is easy to lock the watch , happen error.
·future Method cannot call another method that is also future Methods
4. example :
There are two ways , One does not specify @future, Another specifies @future, And verify whether the results are correct .
public with sharing class ExampleFuture {
public static void methodNoFuture(Set<Id> idsSet) {
String sql = 'SELECT Id,Name FROM Opportunity where Id in :idsSet';
List<Opportunity> opps = Database.query(sql);
List<Opportunity> newOppList = new List<Opportunity>();
for(Opportunity opp : opps) {
opp.stageName = 'Closed Won';
newOppList.add(opp);
}
update newOppList;
System.debug('>>>>>>>>methodNoFuture::'+System.isQueueable());
}
@future
public static void methodFuture(Set<Id> idsSet) {
String sql = 'SELECT Id,Name FROM Opportunity where Id in :idsSet';
List<Opportunity> opps = Database.query(sql);
List<Opportunity> newOppList = new List<Opportunity>();
for(Opportunity opp : opps) {
opp.stageName = 'Closed Won';
newOppList.add(opp);
}
update newOppList;
System.debug('>>>>>>>>methodFuture::'+System.isQueueable());
}
}Below is the test class , The difference is to call future When the method is used , The place to call must be 【Test.startTest();】 and 【Test.stopTest();】 Between , Otherwise, the call will not succeed .
@isTest
public with sharing class ExampleFutureTest {
static testMethod void FutureTest001() {
List<Opportunity> oppList = new List<Opportunity>();
for(integer i = 0; i<200; i++){
Opportunity oppItem = new Opportunity(Name='methodNoFutureOpportunity'+ i,
StageName='Perception Analysis',
CloseDate = Date.Today(),
DeleteFlg__c = true);
oppList.add(oppItem);
}
insert oppList;
Map<Id, Opportunity> oppsMap = new Map<Id, Opportunity>(oppList);
ExampleFuture.methodNoFuture(oppsMap.keySet());
List<Opportunity> oppUpdateList = [SELECT Id,StageName FROM Opportunity WHERE DeleteFlg__c = true];
System.assertEquals(200, oppUpdateList.size());
if (oppUpdateList != null && oppUpdateList.size() >0) {
for (Opportunity oppUpdate : oppUpdateList) {
System.assertEquals('Closed Won', oppUpdate.StageName);
}
}
}
static testMethod void FutureTest002() {
List<Opportunity> oppList = new List<Opportunity>();
for(integer i = 0; i<200; i++){
Opportunity oppItem = new Opportunity(Name='methodFutureOpportunity'+ i,
StageName='Perception Analysis',
CloseDate = Date.Today(),
DeleteFlg__c = true);
oppList.add(oppItem);
}
insert oppList;
Map<Id, Opportunity> oppsMap = new Map<Id, Opportunity>(oppList);
Test.startTest();
ExampleFuture.methodFuture(oppsMap.keySet());
Test.stopTest();
List<Opportunity> oppUpdateList = [SELECT Id,StageName FROM Opportunity WHERE DeleteFlg__c = true];
System.assertEquals(200, oppUpdateList.size());
if (oppUpdateList != null && oppUpdateList.size() >0) {
for (Opportunity oppUpdate : oppUpdateList) {
System.assertEquals('Closed Won', oppUpdate.StageName);
}
}
}
}Execution results :
sObjects That Cannot Be Used Together in DML Operations
some sObject Upper DML The operation cannot be the same as other operations in the same transaction sObject Upper DML Mixed execution , For example, when inserting Account Table data , It is necessary to insert at the same time Role Of User, Now insert user Method needs to be specified @future
public with sharing class ExampleMixedDMLFuture {
public static void useFutureMethod() {
// First DML operation
Account a = new Account(Name='Acme');
insert a;
System.debug('>>>>>>>>useFutureMethod11::'+System.isQueueable());
// This next operation (insert a user with a role)
// can't be mixed with the previous insert unless
// it is within a future method.
// Call future method to insert a user with a role.
ExampleInsertUserFuture.insertUserWithRole(
'[email protected]', 'xiang',
'[email protected]', 'yu');
System.debug('>>>>>>>>useFutureMethod22::'+System.isQueueable());
}
}public with sharing class ExampleInsertUserFuture {
@future
public static void insertUserWithRole(String uname, String al, String em, String lname) {
System.debug('>>>>>>>>insertUserWithRole111::'+System.isQueueable());
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User u = new User(alias = al, email=em,
emailencodingkey='UTF-8', lastname=lname,
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username=uname);
insert u;
System.debug('>>>>>>>>insertUserWithRole222::'+System.isQueueable());
}
}Test class :
@isTest
public with sharing class ExampleMixedDMLFutureTest {
@isTest static void test1() {
User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
// System.runAs() allows mixed DML operations in test context
System.runAs(thisUser) {
// startTest/stopTest block to run future method synchronously
Test.startTest();
ExampleMixedDMLFuture.useFutureMethod();
Test.stopTest();
}
// The future method will run after Test.stopTest();
// Verify account is inserted
Account[] accts = [SELECT Id from Account WHERE Name='Acme'];
System.assertEquals(1, accts.size());
// Verify user is inserted
User[] users = [SELECT Id from User where username='[email protected]'];
System.assertEquals(1, users.size());
}
}Execution results :
Execute... In the same transaction DML In operation , The following cannot be sObject And others sObject Use it together
- FieldPermissions
- Group
- GroupMember
- ObjectPermissions
- PermissionSet
- PermissionSetAssignment
- QueueSObject
- ObjectTerritory2AssignmentRule
- ObjectTerritory2AssignmentRuleItem
- RuleTerritory2Association
- SetupEntityAccess
- Territory2
- Territory2Model
- UserTerritory2Association
- User
边栏推荐
- [technical grass planting] use the shared image function to realize the offline switching from CVM to LH
- What is the same origin policy?
- .NET 中的 Worker Service 介绍
- Six complete open source projects, learning enough at a time
- 逆向工具IDA、GDB使用
- Tupu software intelligent wind power: operation and maintenance of digital twin 3D wind turbine intelligent equipment
- 2.摄像机标定
- Multi store drug inventory system source code large chain drugstore management system source code
- What are the good solutions for industrial control safety of production line
- 量化投资模型——高频交易做市模型相关(Avellaneda & Stoikov’s)研究解读&代码资源
猜你喜欢

Tiktok practice ~ password retrieval

Under the background of aging, the comprehensive energy efficiency management platform escorts hospitals

人工智能技术岗位面试要注意什么?
![[proteus simulation] example of T6963C driving pg12864 (with Chinese and English display)](/img/e7/d36750c729b76f18418589356706f1.png)
[proteus simulation] example of T6963C driving pg12864 (with Chinese and English display)

Web site SSL certificate

Docker deploy redis

1. < tag dynamic programming and path combination problem > lt.62 Different paths + lt.63 Different paths II

Recommend 4 flutter heavy open source projects

Notepad++ practical function sharing (common methods for replacing the end and beginning of regular lines, text comparison function, etc.)

Six necessary open source projects for private activities
随机推荐
Comment utiliser l'entrepôt de données pour créer une table de synchronisation
跟着CTF-wiki学pwn——ret2text
Interpreting the "four thoughts" of Wal Mart China President on the transformation and upgrading of physical retail
[interview experience package] summary of experience of being hanged during interview (I)
fatal: The upstream branch of your current branch does not match the name of your current branch.
Leetcode——链表笔试题
return、const、volatile关键字
Docker deploy redis
抖音实战~手机号密码一键注册登录流程(限制手机终端登录)
2. camera calibration
When the IOT network card device is connected to easycvr, how can I view the streaming IP and streaming time?
Keywords such as extern and struct
混沌工程,了解一下
1.< tag-动态规划和路径组合问题>lt.62. 不同路径 + lt.63. 不同路径 II
Another short video app with high imitation and eye opening
String s = new string ("XYZ") how many string objects are created?
Cvpr2019/ image translation: transgaga: geometry aware unsupervised image to image translation
. Net
How to achieve energy-saving and reasonable lighting control in order to achieve the "double carbon" goal
逆向工具IDA、GDB使用