Latest Posts

Archives [+]

The Apache Sling Scheduler

The Apache Sling Scheduler enables you to easily schedule jobs within your application. Jobs can be executed at a specific time, regularly at a given period or at the time given by a cron expression by leveraging the Sling scheduler service.
Let's get some hands on code.
The job consists in writing "Executing the job" in the logs. You'd define it as follows:

final Runnable job = new Runnable() {
    public void run() {
        log.info("Executing the job");
    }
};

To execute the previous job at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday, you can use the addJob() method with the following parameters:

String schedulingExpression = "0 15 10 ? * MON-FRI";
this.scheduler.addJob("myJob", job, null, schedulingExpression, true);

Refer to http://www.docjar.com/docs/api/org/quartz/CronTrigger.html
 to find out how to define scheduling expressions.

To execute the previous job every 3 minutes, you can use the addPeriodicJob() method with the following parameters:

long period = 3*60; //the period is expressed in seconds
this.scheduler.addPeriodicJob("myJob", job, null, period, true);

To execute the previous job at a specific date (on January 10th 2020), you can use the fireJobAt() method with the following parameters:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String date = "2020/01/10";
java.util.Date fireDate = formatter.parse(date);
this.scheduler.fireJobAt("myJob", job, null, fireDate);

The code implementing a service that simultaneously executes the job based on the three different kinds of scheduling is attached to this post.

It is also possible to schedule jobs by leveraging the whiteboard pattern.

The following job is executed every minute by setting scheduler.expression to the cron expression "0 * * * * ?":

package sling.docu.examples;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @scr.component
 * @scr.service interface="java.lang.Runnable"
 * @scr.property name="scheduler.expression" value="0 * * * * ?"
 */
public class ScheduledCronJob implements Runnable {

    /** Default log. */
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    
    public void run() {
        log.info("Executing a cron job (job#1) through the whiteboard pattern");
    }
//
}

Have fun scheduling with Sling!

* HelloWorldScheduledService.java
HelloWorldScheduledService.java