Tag Archives: Apex

Schedule Apex Jobs Using Cron Expression in Salesforce

To schedule an apex job using Salesforce Cron Expression, you need to use System.Schedule apex method.

Scheduled Class:

global class AccountBatchScheduled implements Schedulable {
    global void execute(SchedulableContext ctx) {
        //Write your logic
    }
}

Scheduled Apex Class Using Cron Expression:

AccountBatchScheduled apexSch = new AccountBatchScheduled(); 
//Seconds, Minutes, Hours, Day of month, Month, Day of week, Optional year 
String CRON_EXP = '0 0 0 3 9 2 ?';
String jobID = System.schedule('AccountBatchScheduled Job', CRON_EXP, apexSch);

Cron Expression Values:

Name Values Special Characters
Seconds 0–59 None
Minutes 0–59 None
Hours 0–23 None
Day_of_month 1–31 , – * ? / L W
Month 1–12 or the following:

  • JAN
  • FEB
  • MAR
  • APR
  • MAY
  • JUN
  • JUL
  • AUG
  • SEP
  • OCT
  • NOV
  • DEC
, – * /
Day_of_week 1–7 or the following:

  • SUN
  • MON
  • TUE
  • WED
  • THU
  • FRI
  • SAT
, – * ? / L #
optional_year null or 1970–2099 , – * /

Cron Expression Special Characters:

Special Character Description
, Delimits values. For example, use JAN, MAR, APR to
specify more than one month.
Specifies a range. For example, use JAN-MAR to specify
more than one month.
* Specifies all values. For example, if
Month is specified as *, the job is
scheduled for every month.
? Specifies no specific value. This is only
available for Day_of_month and
Day_of_week, and is generally
used when specifying a value for one and not the
other.
/ Specifies increments. The number before the
slash specifies when the intervals will begin, and
the number after the slash is the interval amount.
For example, if you specify 1/5 for
Day_of_month, the Apex class
runs every fifth day of the month, starting on the
first of the month.
L Specifies the end of a range (last). This
is only available for
Day_of_month and
Day_of_week. When used with
Day of month, L always means the
last day of the month, such as January 31,
February 29 for leap years, and so on. When used
with Day_of_week by itself, it
always means 7 or SAT. When used with a
Day_of_week value, it means the
last of that type of day in the month. For
example, if you specify 2L, you are
specifying the last Monday of the month. Do not
use a range of values with L as the results
might be unexpected.
W Specifies the nearest weekday
(Monday-Friday) of the given day. This is only
available for Day_of_month. For
example, if you specify 20W, and the 20th
is a Saturday, the class runs on the 19th. If you
specify 1W, and the first is a Saturday, the
class does not run in the previous month, but on
the third, which is the following Monday.

Use the L and W together to specify the last weekday
of the month.
# Specifies the nth day of
the month, in the format weekday#day_of_month.
This is only available for
Day_of_week. The number before
the #
specifies weekday (SUN-SAT). The number after the # specifies the
day of the month. For example, specifying 2#2 means the
class runs on the second Monday of every month.

Cron Expression Examples :

Expression Description
0 0 13 * * ? Class runs every day at 1 PM.
0 0 22 ? * 6L Class runs the last Friday of every month
at 10 PM.
0 0 10 ? * MON-FRI Class runs Monday through Friday at 10
AM.
0 0 20 * * ? 2010 Class runs every day at 8 PM during the
year 2010.

How to write batch apex class in Salesforce?

What is Batch Apex Class:

The class that implements Database.Batchable interface can be executed as a Batch Apex Class. Batch jobs can be programmatically invoked at runtime using Apex.

Batch Apex Governor Limits:

  • All methods in the class must be defined as global or public.
  • Up to five queued or active batch jobs are allowed for Apex.
  • A user can have up to 50 query cursors open at a time. For example, if 50 cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Note that this limit is different for the batch Apexstart method, which can have up to 15 query cursors open at a time per user. The other batch Apex methods have the higher limit of 50 cursors.
  • Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors, 50 batch cursors, and 50 Visualforce cursors open at the same time.
  • A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.
  • If the start method returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits.
  • If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200, and then passes each batch to the execute method.Apex governor limits are reset for each execution of execute.
  • The start, execute, and finish methods can implement up to 10 callouts each.
  • Batch executions are limited to 10 callouts per method execution.
  • The maximum number of batch executions is 250,000 per 24 hours.
  • Only one batch Apex job’s start method can run at a time in an organization. Batch jobs that haven’t started yet remain in the queue until they’re started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running.

Why we use Batch Class:

We use batch Apex to build complex DML operations for bulk records or long-running processes that run on thousands of records on the Force.com platform.
The Database.Batchable interface contains three methods that must be implemented.

start method:

global Database.QueryLocater start(Database.BatchableContext bc) {} 
  • The start method is called at the beginning of a batch Apex job.
  • This method is Used to collect the records or objects to pass to the interface method execute.
  • This method returns either a Database.QueryLocator object or an Iterable that contains the records or objects passed into the job.
  • Query executed in the start method will return maximum 5,00,00000 records in a transaction.

execute method:

global void execute(Database.BatchableContext bc , List scope) {} 
  • The execute method is called for each batch of records passed to the method.
  • This method is used for do all the processing for data.
  • This method takes the following:
    • A reference of Database.BatchableContext object.
    • A list of sObject records.
  • Batches of records are not guaranteed to execute in the order they are received from the start method.

finish method:

global void finish(Database.BatchableContext bc) {}
  • The finish method is called after all batches are processed.
  • This method is used to send confirmation emails or execute post-processing operations.
  • This method takes only one argument a reference of Database.BatchableContext object.
  • This method is called when all the batches are processed.

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.

Here is an example of batch class.

Sample Code:

global class batchAccountUpdate implements Database.Batchable<sobject> {
 
    global Database.QueryLocator start(Database.BatchableContext bc){
     
        String query = 'SELECT Id, Name FROM Account';
        return Database.getQueryLocator(query);
    }
     
    global void execute(Database.BatchableContext bc, List<account> scope) {
     
        for(Account a : scope) {
            a.Name = a.Name + 'Updated';
        }
        update scope;
    } 
     
    global void finish(Database.BatchableContext bc) {
     
    }
}

If you want to notify admin on successful run, then in that case, create an email using this code below and send email by adding this code on finish method.

global void finish(Database.BatchableContext bc){
	Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
	mail.setToAddresses(new String[] {email});
	mail.setReplyTo('info@biswajeetsamal.com');
	mail.setSenderDisplayName('Account Batch Processing');
	mail.setSubject('Account Batch Process Completed');
	mail.setPlainTextBody('Account Batch Process has completed');
	Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

Call the Batch Class:

batchAccountUpdate batchAcc = new batchAccountUpdate();
database.executebatch(batchAcc, 10);

Note: If batch size is not mentioned the default batch size is 200 and the maximum batch size is 2000.

Salesforce Create User Using Apex

Sample Code:

//Get Profile Id
Profile objProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
//Add User Information
User objUser = new User();
objUser.FirstName='Biswajeet';
objUser.LastName = 'Samal';
objUser.Alias = 'Biswa';
objUser.Email = 'itzbiswajeet@gmail.com';
objUser.Username = 'itzbiswajeet@gmail.com';
objUser.ProfileId = profileId.id;
objUser.TimeZoneSidKey = 'GMT';
objUser.LanguageLocaleKey = 'en_US';
objUser.EmailEncodingKey = 'UTF-8';
objUser.LocaleSidKey = 'en_US';
//Insert User
Insert objUser;

Get Default Record Types For Current User Profile On Specific Object Using Apex

Sample Code:

//Get all record types on Account object
List<Schema.RecordTypeInfo> recordTypeInfoList = Account.SObjectType.getDescribe().getRecordTypeInfos();
String defaultRecordTypeId = '';
for(RecordTypeInfo info: recordTypeInfoList) {
    //Check default record type
    if(info.isDefaultRecordTypeMapping()){
        defaultRecordTypeId = info.getRecordTypeId();
        break;
    }
}
System.debug('DefaultRecordTypeId-' + defaultRecordTypeId);

Calculate The Difference Between Two DateTime Fields In Salesforce Apex

Sample Code:

Account acc = [Select Id, Name, CreatedDate, LastModifiedDate From Account LIMIT 1];
Long createdDateTime = acc.CreatedDate.getTime();
Long modifiedDateTime = acc.LastModifiedDate.getTime();
Decimal diffMilliSecs = Decimal.valueOf(modifiedDateTime - createdDateTime);

Decimal dDays = diffMilliSecs/1000/60/60/24;
Integer iDays = Integer.valueOf(math.floor(dDays));
Decimal remainderDays = dDays- iDays;

Decimal dHours = remainderDays * 24;
Integer iHours = Integer.valueOf(math.floor(dHours));
Decimal remainderHours = dHours - iHours;

Decimal dMinutes = remainderHours * 60;
Integer iMinutes = Integer.valueOf(math.floor(dMinutes));
Decimal remainderMinutes = dMinutes - iMinutes;

Decimal dSeconds = remainderMinutes * 60;
Integer iSeconds = Integer.valueOf(math.floor(dSeconds));
Decimal remainderSeconds = dSeconds - iSeconds;

System.debug('Days: ' + iDays+' - '+'Hours: ' + iHours+' - '+'Minutes: ' + iMinutes+' - '+'Seconds: ' + iSeconds);