# Write Apex that creates a Service Appointment for a Work Order with a 60-minute duration and a scheduling window.

**Topic:** Field Service · **Difficulty:** Medium · **Tags:** Apex, Service Appointment, DML

Read it on the site: https://www.forcechallenges.com/interview-questions/write-apex-that-creates-a-service-appointment-for-a-work-order-with-a-60-minute-duration-and-a-scheduling

## Answer

A Service Appointment is created against a parent record (such as a Work Order) with a scheduling window and duration.

```apex
public with sharing class AppointmentService {
    public static ServiceAppointment createFor(Id workOrderId, Integer windowDays) {
        ServiceAppointment sa = new ServiceAppointment(
            ParentRecordId = workOrderId,
            EarliestStartTime = System.now(),
            DueDate = System.now().addDays(windowDays),
            Duration = 60,
            DurationType = 'Minutes'
        );
        insert sa;
        return sa;
    }
}
```

**Notes**
- `ParentRecordId` links the appointment to the Work Order.
- The appointment starts with no schedule. The scheduling engine or a dispatcher then assigns it.
- For bulk creation, build a list and insert once outside any loop.

---
Source: ForceChallenges · last updated 2026-10-28
