简体   繁体   中英

How to create a background job in AEM as a Cloud?

I want to create a daily background job to be executed by AEM. I read an aem document and apache sling official site, and I thought I need two classes.

  • a service class that register the job to JobManager.
  • a consumer class that do the job.

So I tried these code, but my job was not executed.

service class

import org.apache.sling.event.jobs.JobManager;
import org.apache.sling.event.jobs.JobBuilder.ScheduleBuilder;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class MyJobService {
    private static final Logger logger = LoggerFactory.getLogger(MyJobService.class);
    
    @Reference
    private JobManager jobManager;

    public static final String JOB_TOPIC = "my/sample/jobtopic";

    public void startScheduledJob() {
        ScheduleBuilder scheduleBuilder = jobManager.createJob(JOB_TOPIC).schedule();
       
        scheduleBuilder.hourly(9, 0); // execute daily at AM9:00
        if (scheduleBuilder.add() == null) {
            logger.error("myjobservice error");
        }
    }
}

job consumer class

import org.apache.sling.event.jobs.Job;
import org.apache.sling.event.jobs.consumer.JobConsumer;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(
    immediate = true,
    service = JobConsumer.class,
    property = {
        JobConsumer.PROPERTY_TOPICS + "=my/sample/jobtopic"
    }
)
public class MyJobConsumer implements JobConsumer {
    private static final Logger logger = LoggerFactory.getLogger(MyJobConsumer.class);
    @Override
    public JobResult process(Job job) {
        String topic = job.getTopic();
        logger.info("this message is from myjobconsumer. topic is " + topic);
        return JobResult.OK;
    }  
}

Do I need another class or some configurations? Does My code have something wrong?

If you annotate a method with @Activate it will be called when the component starts.

@Activate public void startScheduledJob()

I guess you want your job to run on startup. Another option would be to let MyJobService be a servlet and call it from outside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM