D365FO create batch job by code

Automation needs can be varied. One of them is to put the task in batch automatically. 

Batch framework queue consist of mainly two tables - Batch and BatchJob. When manually a new batch job is created, at one record is created in BatchJob table and at least one record is created in Batch (batch task) table. It is Batch table which contain the information about the class/method to execute and have the relevant parameter information.

There can be other variations like multiple tasks in a batch, their dependencies etc. but that is not what I am writing about today.

Luckily we don't have to manually deal with these tables but we have a got an API named BatchHeader. This API has very simple methods which can be used to run any runnable task (having main method and without user interaction)  in batch.

Let's take an example of a class implementing SysOperationFramework class.

BatchHeader batchHeader = BatchHeader::construct();

batchHeader.parmCaption("<Some caption of the batch job>");

batchHeader.parmBatchGroup('<Batch group id>');

batchHeader.parmExecutingBy('<User id>');

SysOperationServiceController sysOperationServiceController = new SysOperationServiceController(

                classStr(<ClassName>),

                methodStr(<ClassName>, <MethodName>),

                SysOperationExecutionMode::Synchronous);

<DataContractClassName> dataContract = sysOperationServiceController.getDataContractObject as <DataContractClassName>;

//Use parm methods of data contract to fill data in the contract

batchHeader.addTask(sysOperationServiceController);

batchHeader.save();


The above code is self-explanatory. In brief, you need to create an object of API BatchHeader. Then parm optional items like caption, batch group etc. Create an instance of your controller class (or any class which you want to run. it should have 'main' method to guide the flow). 

Add all the parameters to that controller class instance. This is generally done by a dialog when done manually. As the whole process is automatic, all the required entries need to be saved by code. 

Once done, add this as a task to batch header instance and save the batch header. This will create a new batch job in the batch queue.


Comments

Popular Posts