AEM Sling Jobs
OSGI content event admin has no information about the importance of content of any event and how important is to run this event.
There are multiple other ways we can run an event using event handlers, event listeners, scheduled jobs using scheduler. Why we need Sling Jobs, if we have all these options available.
Sling Jobs will always run again and again if gets fail for some reason or something went wrong.
If we are using event handlers or schedulers to execute or run code at particular time and at the same time if some how system gets fail or crash will not allow execution of required code. But, in case of Sling jobs
it will try again once system gets up and makes sure the task is done.
Follow below steps to implement Sling Jobs:
- Create a class and implements JobConsumer interface. Provide required topics name as part of component property annotation. Override process method having Job as a parameter and return Job result as success, failure, etc.
package com.javadoubts.core.jobs;
import org.apache.sling.event.jobs.Job;
import org.apache.sling.event.jobs.consumer.JobConsumer;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(service = JobConsumer.class,
immediate = true,
property = {
Constants.SERVICE_DESCRIPTION + "= Practice Job",
JobConsumer.PROPERTY_TOPICS + "=practice/job"
})
public class PracticeJob implements JobConsumer{
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public JobResult process(Job job) {
try {
logger.error("Practice JOB Called *******");
return JobConsumer.JobResult.OK;
} catch (Exception e) {
logger.error("Exception ", e);
return JobResult.FAILED;
}
}
}
2. Use below out of the box JobManager interface from org.apache.sling.event.jobs package to add sling job in system. Add Sling job using addJob() method having topics practice/job as first parameter and properties as part of second parameter.
3. Hit servlet using below path to call servlet which will help us to add job to the system and execute. Execution of Job process method will print below inline log.
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.