# Background work on AEM as a Cloud Service — jobs, schedulers, listeners, workflows

> **Verified:** 2026-09 against https://sling.apache.org/documentation/bundles/apache-sling-eventing-and-job-handling.html and https://experienceleague.adobe.com/en/docs/experience-manager-learn/cloud-service/developing/advanced/run-job-on-leader-instance-in-aem-author

Open this when choosing a mechanism for work that happens outside a request, or when something runs too often, too late, or on the wrong tier.

## Choose the mechanism

| Need | Use | Why not the others |
|---|---|---|
| Must happen exactly once, may take seconds or minutes | **Sling Job** (`JobManager#addJob`) | Persisted, retried, survives pod recycling |
| Must happen on a schedule and must not be skipped | **Scheduled Sling Job** (`JobBuilder#schedule()`) | Commons `Scheduler` fires once per pod and Adobe states its execution "cannot be guaranteed" |
| Cheap, idempotent, per-pod housekeeping (cache warm-up, metric flush) | Commons `Scheduler` with a cron expression | A job would add repository writes for no benefit |
| React to a content change | `ResourceChangeListener` that **enqueues a job** | Listeners block the observation thread; `EventHandler`/JCR observation is the older, heavier API |
| Human steps, approvals, audit trail | Workflow | Workflows carry a UI, history and permissions a job does not |
| Asset rendition generation | Asset microservices / processing profiles (`aem-assets`) | Custom rendition workflows do not scale on Cloud Service |

## A job consumer

```java
@Component(service = JobConsumer.class,
           property = JobConsumer.PROPERTY_TOPICS + "=acme/price/sync")
public class PriceSyncJobConsumer implements JobConsumer {

    @Override
    public JobResult process(Job job) {
        String path = job.getProperty("path", String.class);
        try {
            // do the work; it must be safe to run twice
            return JobResult.OK;
        } catch (TransientException e) {
            return JobResult.FAILED;   // retried per queue configuration
        } catch (Exception e) {
            return JobResult.CANCEL;   // permanent failure, no retry
        }
    }
}
```

- `JobResult.OK` = done, `FAILED` = retry, `CANCEL` = give up. Delivery is at-least-once, so every consumer must be idempotent: check whether the work is already done before doing it.
- Enqueue with `jobManager.addJob("acme/price/sync", Map.of("path", path))`. Job properties must be serialisable scalars — pass a path, not a `Resource`.
- Keep the payload small. Jobs are stored in the repository; a large map multiplied by a traffic spike becomes a repository problem.

## A scheduled job

```java
ScheduleBuilder schedule = jobManager.createJob("acme/price/sync").schedule();
schedule.cron("0 0 3 * * ?");           // 03:00 every day, one run for the whole author service
schedule.add();                          // returns null and populates the error list on a bad expression
```

Register it from `@Activate` and remove stale schedules with `jobManager.getScheduledJobs()` when the cron expression changes — scheduled jobs persist in the repository across deployments.

## Queue configuration

Factory PID `org.apache.sling.event.jobs.QueueConfiguration`, shipped as `ui.config/.../config.author/org.apache.sling.event.jobs.QueueConfiguration~acme.cfg.json`:

```json
{
  "queue.name": "Acme price sync",
  "queue.topics": ["acme/price/*"],
  "queue.type": "UNORDERED",
  "queue.maxparallel": 2,
  "queue.retries": 5,
  "queue.retrydelay": 60000
}
```

- `queue.type`: `UNORDERED` (parallel), `ORDERED` (one at a time, in order), `TOPIC_ROUND_ROBIN` (fair across topics).
- Putting the config in `config.author` keeps the consumer — and therefore the work — off publish. Publish pods are disposable and their repository writes are lost on recycle, so business jobs belong on author.
- `queue.maxparallel` is the throttle. Raise it only after checking that the work does not saturate the shared thread pool; a runaway queue shows up as author slowness (`aem-performance`).

## Single-execution work on author

Author instances form a cluster, so exactly one pod is the leader. Adobe's documented pattern is a scheduled Sling Job (the job runs once for the cluster) or, for a Commons `Scheduler`, `scheduler.runOn = "SINGLE"`. Publish instances are *not* clustered — each pod is its own leader, so `runOn = "LEADER"` there means "every pod".

## Content mutation and replication

```java
replicator.replicate(session, ReplicationActionType.ACTIVATE, path);
```

- Custom replication agents do not exist on Cloud Service; the agents are managed and reverse replication is unsupported. User-generated data goes to an external store, never to the publish repository.
- Deactivate with `ReplicationActionType.DEACTIVATE`; the preview tier is reached with the same API through its own agent, configured by the platform.
- Always `session.save()`/`resolver.commit()` in batches (a few hundred nodes) inside long jobs, and call `session.refresh(false)` between batches to avoid holding a large changeset in memory.

## Listeners

```java
@Component(service = ResourceChangeListener.class, property = {
    ResourceChangeListener.PATHS + "=/content/acme",
    ResourceChangeListener.CHANGES + "=ADDED",
    ResourceChangeListener.CHANGES + "=CHANGED"
})
public class PageChangeListener implements ResourceChangeListener { /* enqueue a job, nothing else */ }
```

Scope `PATHS` as narrowly as possible — a listener on `/content` runs for every authoring keystroke in every site. Return in milliseconds: no queries, no HTTP, no `commit()`.
