Schedule Apex (Salesforce UI and CRON Expression – Asynchronous Apex)

Introduction

Scheduled Apex allows developers to schedule a class to run at specific intervals using CRON expressions or the Salesforce UI.

Key Features

  • Automates recurring tasks.
  • Flexible scheduling using CRON expressions.

Syntax for a Scheduled Apex Class

A class must implement the Schedulable interface.

global class ScheduledExample implements Schedulable {
    global void execute(SchedulableContext SC) {
        List<Account> accounts = [SELECT Id, Name FROM Account];
        for (Account acc : accounts) {
            acc.LastModifiedDate = System.now();
        }
        update accounts;
    }
}

Scheduling Through Salesforce UI
  • Navigate to Setup > Apex Classes > Schedule Apex.
  • Select the class and set the frequency, start date, and time.

Scheduling Using CRON Expression
String cronExp = '0 0 12 * * ?'; // Every day at 12 PM
System.schedule('Daily Account Update', cronExp, new ScheduledExample());

CRON Expression Format
Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year

Example CRON expressions:
  • 0 0 6 * * ? – Every day at 6 AM.
  • 0 0 12 ? * MON-FRI – Every weekday at 12 PM.

Limitation for Asynchronous

From / WhatCall @future methodSystem.enqueueJob()Database.executeBatch()System.schedule()
Anonymous Apex5050100100
@AuraEnabled method5050100100
@future method010100
Queueable execute()501100100
Schedulable execute()5050100100
Batch start()010100
Batch execute()010100
Batch finish()010100
Platform Event trigger5050100100
Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *