How can developers call the Salesforce Field Service scheduling engine from Apex (FSL.ScheduleService), and what should they watch out for?
Answer
The Field Service managed package (namespace FSL) exposes global Apex classes to schedule and book appointments from code.
Common APIs
FSL.ScheduleService.schedule(policyId, serviceAppointmentId): schedules one appointment using a Scheduling Policy.FSL.AppointmentBookingService: returns available slots for a customer-facing booking flow.FSL.OAAS: starts optimization from code.
apex
public with sharing class SchedulerQueueable implements Queueable, Database.AllowsCallouts {
private Id saId;
public SchedulerQueueable(Id saId) { this.saId = saId; }
public void execute(QueueableContext ctx) {
Id policyId = [SELECT Id FROM FSL__Scheduling_Policy__c
WHERE Name = 'Customer First' LIMIT 1].Id;
FSL.ScheduleResult result = FSL.ScheduleService.schedule(policyId, saId);
if (result == null) {
// log: appointment could not be scheduled
}
}
}
Important points
- Scheduling calls out to the engine, so run it asynchronously (Queueable with callouts), not directly in a trigger.
- The appointment needs a geocoded address, a territory and valid dates.