可排队的作业与未来的方法相似,因为它们都排队等待执行,但它们为您提供了这些额外的好处。
public class AsyncExecutionExample implements Queueable {
public void execute(QueueableContext context) {
Account a = new Account(Name='Acme',Phone='(415) 555-1212');
insert a;
}
}
ID jobID = System.enqueueJob(new AsyncExecutionExample());
AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];
@isTest
public class AsyncExecutionExampleTest {
static testmethod void test1() {
// startTest/stopTest block to force async processes
// to run in the test.
Test.startTest();
System.enqueueJob(new AsyncExecutionExample());
Test.stopTest();
// Validate that the job has run
// by verifying that the record was created.
// This query returns only the account created in test context by the
// Queueable class method.
Account acct = [SELECT Name,Phone FROM Account WHERE Name='Acme' LIMIT 1];
System.assertNotEquals(null, acct);
System.assertEquals('(415) 555-1212', acct.Phone);
}
}
队列Trigger
public class InvokeQueueBatchHandler implements Triggers.Handler{
public void handle(){
//查询是否有在运行的Queue Batch
List list_Status = new List{'Queued','Processing','Preparing','Holding'};
if([select id from AsyncApexJob
where Status in: list_Status
and ApexClass.Name ='OutboundQueueBatch'
limit 1].size() == 0)
{
Database.executeBatch(new OutboundQueueBatch(),1);
}
}
}
队列Batch
global class OutboundQueueBatch implements Database.Batchable,Database.AllowsCallouts {
public String query;
global OutboundQueueBatch() {
this.query = 'Select Id,DeliveryNote__c,Status__c From Outbound_Queue__c Where Status__c = \'未处理\'';
}
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, list scope) {
List listQueue = (list)scope;
for(Outbound_Queue__c oQueue : listQueue){
if(oqueue.DeliveryNote__c != null){
//call out,传递运输通知单ID
CRMSalesOrderController.getStOrder(oQueue.DeliveryNote__c);
}
//更新状态
oqueue.Status__c='完成';
}
update listQueue;
}
global void finish(Database.BatchableContext BC) {
//队列中存在尚未处理完的数据,重新启用batch。
List listQueue = Database.query(query);
if(listQueue.size() > 0 && !System.Test.isRunningTest()){
Database.executeBatch(new OutboundQueueBatch(), 1);
}
}
}