Sub topic 5
Scheduling from Setup
This chapter assumes you can write a Schedulable class and read a cron expression, both covered earlier in this tutorial. It also assumes you know your way around Setup. Here you schedule a job without writing any scheduling code, and you learn what that approach can't do.
What the Setup scheduler is
Salesforce lets you schedule a Schedulable class from a form in Setup. You don't call System.schedule or write a cron expression. You pick the class, a frequency, a date range, and a preferred time. Salesforce converts your choices into a cron expression and creates the same kind of CronTrigger record that System.schedule creates.
The two methods differ in what they can express, not in how the job runs. Once the job exists, Apex can't tell how it was created.
Opening the form
- In Setup, enter
Apex Classesin Quick Find and open it. - Click Schedule Apex.
- Fill in the form and click Save.
The form has these fields:
| Field | What it does |
|---|---|
| Job Name | A label for the job. It must be unique among your scheduled jobs. |
| Apex Class | The class to run. The lookup lists only classes that implement `Schedulable`. |
| Frequency | Weekly or Monthly. No other choices exist. |
| Start and End | The first and last dates on which the job may run. |
| Preferred Start Time | The time of day you would like the job to run. |
If you enter Escalate stale cases as the job name, you can find the job under that name later, in Setup and in a CronTrigger query.
Choosing a frequency
The form supports two frequencies. This is the main limit of the UI.
- Weekly. You tick one or more days of the week. The job runs on each ticked day between the start and end dates.
- Monthly. You choose either a day of the month (for example, the 1st) or a position within the month (for example, the last Friday, or the second Tuesday).
You can't ask for "every hour" or "every 15 minutes", and you can't ask for "daily" except by ticking all seven weekdays. If you need to run more often than once a day, you must use System.schedule.
The table shows the equivalent cron expression for common UI choices. The Apex cron day-of-week numbers run from 1 (Sunday) to 7 (Saturday).
| UI choice | Equivalent cron expression |
|---|---|
| Weekly on Mon, Wed, Fri at 6:00 AM | `0 0 6 ? * MON,WED,FRI` |
| Monthly on day 1 at 2:00 AM | `0 0 2 1 * ?` |
| Monthly on the last day, at 2:00 AM | `0 0 2 L * ?` |
| Monthly on the last Friday at 2:00 AM | `0 0 2 ? * 6L` |
| Monthly on the second Tuesday at 2:00 AM | `0 0 2 ? * 3#2` |
The last two rows show that the UI is not weaker than code for monthly patterns. The "nth weekday of the month" option is a convenient way to get 6L or 3#2 without remembering the syntax.
Start time is a preference
The field is called Preferred Start Time because Salesforce does not guarantee the exact second or minute. The job is placed in a queue and starts when capacity is available, which may be a little after the time you chose. Plan for a short delay, and never write code that assumes the job started at a precise moment. If the logic depends on a time, read it from the data instead, as in the example below.
The time you pick is interpreted in your user time zone, so two administrators in different zones who pick "6:00 AM" get different real times. The user who schedules the job also determines the context the job runs under, which is covered in the next section.
Who the job runs as
A scheduled job runs as the user who scheduled it. Apex runs in system mode by default, so object and field permissions are not enforced unless your code enforces them. The running user still matters for these things:
- Record ownership. Records created by the job are owned by the scheduling user unless your code sets another owner.
- Audit fields.
CreatedByIdandLastModifiedByIdshow that user. - Email. Emails sent by the job use that user as the sender context.
- Time zone. Dates and times in the job follow that user's settings.
If a named administrator schedules a job and later leaves the company, the job's ownership and history point at a person who no longer works there. Many teams create a dedicated integration user and schedule jobs while logged in as that user. Doing that from the UI means logging in as that user, or using the "login as" feature if your org allows it.
The class needs a no-argument constructor
The Setup form can't pass arguments to your class. It creates an instance with the default constructor. If your class only has constructors that take parameters, it won't work from the UI.
public class ReportRefreshJob implements Schedulable {
private final Integer daysBack;
// Used by the Setup UI and by code that wants the default.
public ReportRefreshJob() {
this(7);
}
// Used by code that wants a different window.
public ReportRefreshJob(Integer daysBack) {
this.daysBack = daysBack;
}
public void execute(SchedulableContext sc) {
Date since = Date.today().addDays(-daysBack);
List<Opportunity> recent = [
SELECT Id, Description
FROM Opportunity
WHERE CloseDate >= :since
LIMIT 200
];
for (Opportunity o : recent) {
o.Description = 'Reviewed on ' + String.valueOf(Date.today());
}
update recent;
}
}This class has two constructors. The Setup form uses the first, so the job looks back seven days. Code that calls System.schedule('Weekly review', cron, new ReportRefreshJob(30)) can choose a different window. This is a common pattern: put sensible defaults in the no-argument constructor so the same class can be scheduled both ways.
If a class has no explicit constructors, Apex provides a no-argument constructor for you, so the problem only appears once you add a constructor with parameters.
Viewing and managing jobs
To see scheduled jobs, enter Scheduled Jobs in Quick Find in Setup. The page lists every scheduled job in the org, whether it was created from the UI or from code. The columns include:
- the job name and the user who submitted it
- the last run time and the next run time
- the type (Scheduled Apex jobs show this as such)
- links to manage or delete the job
Use Del to remove a job. This has the same effect as System.abortJob. The job disappears from the list and won't run again.
There is no Edit action for a scheduled Apex job. To change the frequency, you delete the job and schedule a new one. This also means a job's history ends when you replace it, including its TimesTriggered count.
Finding UI-created jobs from Apex
A job created from Setup is a CronTrigger record like any other. This query lists all Scheduled Apex jobs, with the cron expression Salesforce generated from your form choices:
List<CronTrigger> jobs = [
SELECT Id, CronJobDetail.Name, CronExpression, State, NextFireTime, TimesTriggered
FROM CronTrigger
WHERE CronJobDetail.JobType = '7'
ORDER BY NextFireTime
];
for (CronTrigger ct : jobs) {
System.debug(ct.CronJobDetail.Name + ' | ' + ct.CronExpression + ' | next: ' + ct.NextFireTime);
}The value '7' in JobType means Scheduled Apex. Running this after you save the Setup form is a good way to learn how the UI choices map to cron. Compare the CronExpression values with the table above.
Deployment and code-change restrictions
Salesforce protects a class that has a pending scheduled job. While such a job exists, you can't change the class, or classes it references, in the usual ways. Saving an edit in the Developer Console or Setup can fail, and a deployment that includes the class can fail too.
You have two options:
- Delete the scheduled job, make the change, and schedule the job again.
- In Setup, open Deployment Settings and enable the option that allows deployments while Apex jobs are pending or in progress. This is an org-wide setting, so decide deliberately before turning it on.
For this reason, teams that deploy often tend to prefer scheduling from code. A small post-deployment step, or a "scheduler" class, can recreate the jobs after every release. A job created by hand in Setup is easy to forget. After a deployment to a new sandbox or a refresh, it is simply absent, because scheduled jobs are not metadata and don't move with your code.
Limits that apply to both methods
The Setup form and System.schedule share the same org limits:
- An org can have at most 100 scheduled Apex jobs at one time.
- Each execution counts toward your daily asynchronous Apex limit.
- The
executemethod runs under the normal limits for a transaction, so heavy work should be handed to Batch Apex, as covered in a later chapter.
If you hit the job-count limit, the Setup form refuses to save the new job. Delete jobs you no longer need before scheduling more.
Choosing between Setup and code
The Setup form suits an administrator who wants a weekly or monthly job on a class that has sensible defaults, without a developer. System.schedule suits everything else, and it is also the only method you can test, version, and repeat.
Common mistakes
- The class doesn't appear in the lookup. The class must be saved, must compile, and must implement
Schedulable. A class that only implementsDatabase.Batchabledoes not appear. Wrap it in a small scheduled class, as shown in the chapter on handing work to Batch Apex. - The job fails to save. Check the job name for duplicates and check the 100-job limit.
- A deployment fails with a message about scheduled jobs. A pending job references a class in your deployment. Delete the job or change the deployment setting.
- The job runs a little later than expected. This is normal. The start time is a preference.
- The job never fires. Check the start and end dates on the form. A job whose end date has passed is removed from the schedule once it has no further runs.
Summary
The Setup form is a quick way to create weekly and monthly jobs with no code. It requires a no-argument constructor, treats the time as a preference, runs as the scheduling user, and produces the same CronTrigger records as System.schedule. Its restrictions on frequency and its poor fit with deployments are why many teams schedule from code once a job matters.
Exercise
A teammate wants a class to run every 30 minutes and tries to schedule it from the Setup form. What goes wrong, and what should the teammate do instead?
Show answer
The form only offers Weekly and Monthly frequencies, so it can't express a 30-minute interval. The teammate should use System.schedule. A single cron expression can't give a 30-minute step across all hours in some cases, so the usual approach is to schedule two jobs with the minute field set to 0 and 30, for example '0 0 ?' and '0 30 ?'.
Exercise
You scheduled a job from Setup, and later a deployment that includes the job's class fails. Give two ways to get the deployment through, and one drawback of each.
Show answer
Delete the scheduled job, deploy, then schedule the job again. The drawback is that the job's history, including TimesTriggered, is lost and you must remember to recreate it. Alternatively, enable the Deployment Settings option that allows deployments while Apex jobs are pending or in progress. The drawback is that it is an org-wide setting that affects every deployment, not only this one.
Exercise
A class has the constructor public CleanupJob(Integer days) and no other constructor. Why can't it be scheduled from the Setup form, and how do you fix it?
Show answer
The form creates the instance without arguments, and the class has no no-argument constructor. Add a public CleanupJob() constructor that calls this with a default value, such as this(30).