Header Content Footer
Discover best selling sofas, Lounge chairs and get an extra 10% off using the code SEDONA10

One of the AEM functionalities, is the capability to develop a task executed by a specific period of time. It is called Jobs. However, there is a possibility where the requirement come up to execute the functionality in a specific Interval of time. To do that, we have a Scheduler Service.

Scheduler service, how it works?

We have created an osgi service where you can inject the Scheduler service. It has the date time as a String type stored in a resource. The main part is that the code is type as “if”.

As you can see in the code, there is a runnable object which is set as “what to do”. Next you have to check if the job exist. In case it exists, you need to remove it. It will avoid to have lot of threads on the system. However, according to the  documentation, if there is a scheduler task being executed with the same name, it will be removed and replaced automatically by the new one.

@Reference
private Scheduler scheduler;

@Override
public boolean initScheduler(Resource resource , MetaOptionJsonModel metaOptionJsonModel){
    boolean schedulerLaunched = false;
    if (this.scheduler != null) {
            final long delay = 30*1000;
            final Date fireDate = new Date() //Here will be our target date to fire
            if ( fireDate!= null){
               fireDate.setTime(System.currentTimeMillis() + delay);
               final Runnable job3 = new Runnable() {
                  public void run() {
                     //TODO : Write here your functions to execute
                  }
               };
               //creation of job
               try {
                  this.scheduler.unschedule(JOB_NAME);
                  ScheduleOptions options = this.scheduler.AT(fireDate);
                  options.name(JOB_NAME);
                  this.scheduler.schedule(job3,options);
                  schedulerLaunched = true;
               } catch (Exception e) {
                  job3.run();
                  LOG.error("[MetaOptionJob - initScheduler() - Error launching scheduler {} ",e.getMessage());
               }
            }else{
               LOG.error("[MetaOptionJob - initScheduler() - fireDate Date is NULL. Wrong format - current date string {} ",fireDateString);
            }
    }

    return schedulerLaunched;
}

Finally, if the period of time is correct and it works, the last thing you have to do is wait until the task is fired (this is the reason why there are lot of logs).

We hope this post will help you!

If you have more questions, feel free to contact us!