function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
balu palavalasabalu palavalasa 

how do i get job id in finish method before executing batch apex

Hi All,

Before executing Batch apex how am i getting the Jobid of batch apex in finish method as shown below.

Please explain as i am a new to salesforce.

global void finish(Database.BatchableContext BC){

// Get the ID of the AsyncApexJob representing this batch job
// from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.

AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :BC.getJobId()]; ( how do i get job id in finish method before executing batch apex )
// Send an email to the Apex job's submitter notifying of job completion.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {a.CreatedBy.Email}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Sharing Recalculation ' + a.Status); mail.setPlainTextBody ('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures.'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); }

 
v varaprasadv varaprasad
Hi Balu,

Your query is perfect. Please add debug logs and check once.

 AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email    from AsyncApexJob where Id =:BC.getJobId()];
 

Please check once below links.

https://salesforce.stackexchange.com/questions/171641/how-can-i-tell-batch-job-finished-executing-the-finish-method
https://developer.salesforce.com/forums/?id=9060G000000I1BdQAK


Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com​




 
Julian LeahJulian Leah
It was something I didn’t know before so I really found this content interesting. I came to this site through https://jobs-near-me.net/ and had expectations. I am glad that I kept those expectations.