Salesforce Queueable队列

通过使用Queueable接口来控制异步Apex进程。 该接口使您可以将作业添加到队列中并进行监控,与使用未来方法相比,这是运行异步Apex代码的增强方式。
对于长时间运行的Apex流程(例如广泛的数据库操作或外部Web服务标注),您可以通过实现Queueable接口并将作业添加到Apex作业队列来异步运行它们。 这样,您的异步Apex作业将在其自己的线程后台运行,并且不会延迟主Apex逻辑的执行。 每个排队的作业在系统资源可用时运行。 使用Queueable接口方法的好处是某些管理器限制高于同步Apex,例如堆大小限制。

可排队的作业与未来的方法相似,因为它们都排队等待执行,但它们为您提供了这些额外的好处。

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);
        }
    }
}

你可能感兴趣的:(Queueable)