Sling Scheduled Jobs vs Sling Scheduler

Apache Sling and AEM provide 2 different approaches to start processes at a given time or in a given interval. It is not always trivial to make the right decision between these two, and I have seen a few cases of misuse already. Let’s dive into this topic and I will outline in what situation to use the Scheduler and when to use Scheduled Jobs.

Let me outline the differences between these using using a simple table:

 Sling Scheduled JobSling Scheduler
Timing is persisted across restartsYesNo
Start a job via OSGI annotationsNoyes
Start a job via APIYesYes
Trigger on every cluster nodeYes (job execution then follows regular Sling Jobs rules)yes
Trigger just once per clusterYes (job execution then follows regular Sling Jobs rules)Yes (only on cluster leader possible)  
Comparison between Scheduled Jobs and Scheduler

To get a better understanding on these 2 distinct features, I cover a 2 use cases and list which feature is a the better match for it.

Execute code exactly once at a given time

That’s a case for the scheduled job. Even if the job is failing because the executing SLING instance goes down, it will be re-scheduled and tried again.

Here the exactly once semantics means that this is a single job with a global scope. Missing it is not an option. It might be delayed if the triggering date is missed or the execution is aborted, but it will be executed as soon as possible after the scheduled time has passed.

Periodic jobs which effect just a single AEM instance

Use the scheduler whenever you execute periodic/incremental jobs like cleanups, data imports etc. It’s not a problem if you miss their execution on time, but you just make sure that you execute at the next time (or trigger it during startup if necessary).

Another note to choose the right approach: You should not need to create a scheduled job during startup (that means on the startup of services), for these cases it’s normally better to use the Scheduler. There might be rare cases where this it is the right solution, but in the majority of cases you should just use the scheduler in that case.

A word of caution when you use Scheduled Jobs with a periodic pattern: As they are persisted, you need to un-register them when you don’t need them anymore.