This block of codes show you how to run cronjob(s) inside an OSGi component

 

package com.myproject.api.cronjobs;

import com.myproject.api.util.PredefinedParameters;
import com.day.cq.commons.jcr.JcrRecursiveRemove;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.SearchResult;
import java.io.Serializable;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.commons.scheduler.Scheduler;
import org.osgi.framework.Constants;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Component for running cron jobs
 * 
 * @author Sothea Nim
 */
@Component(label = "MyProject Cron Jobs Component", 
    description = "This component is for running cronjobs.",
    immediate = true, metatype = true)
@Properties({
    @Property(name = Constants.SERVICE_DESCRIPTION, value = "Component for running cron jobs"),
    @Property(name = Constants.SERVICE_VENDOR, value = "My Company"),
    @Property(label = "Cleanup Deleted Nodes", 
        description = "For deleting cq nodes flagged with deleted property.",
        name="myproject.cronjobs.cleanupdeletednodes", value = "*/59 * * * * ?") // run every 1 second
})
public class MyProjectCronJobs {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(MyProjectCronJobs.class);
    private static final String CLEANUP_DELETED_NODES="myproject.cronjobs.cleanupdeletednodes";
    private static final JcrRecursiveRemove jcrRecursiveRemove = new JcrRecursiveRemove();
    private static Session session;
    private static ResourceResolver rr;
    
    @Reference
    private Scheduler scheduler;
    
    @Reference
	protected ResourceResolverFactory resourceResolverFactory;
    
    @Reference
    protected QueryBuilder builder;
    
    @Activate
    protected void activate(ComponentContext componentContext) throws Exception {
        
        if (resourceResolverFactory != null) {
            
            rr = resourceResolverFactory.getAdministrativeResourceResolver(null);
            session = rr.adaptTo(Session.class);
            final String legacyPrefix = "prop.";
            Dictionary<?, ?> config = componentContext.getProperties();

            //addJob Method Example.
            String scheduleExp = PropertiesUtil.toString(config.get(CLEANUP_DELETED_NODES), 
                PropertiesUtil.toString(config.get(legacyPrefix + CLEANUP_DELETED_NODES), ""));

            if (scheduleExp.length() > 0) {

                String cleanupDeletedNodes = "CleanupDeletedNodes";
                Map<String, Serializable> cleanupDeletedNodesConfig = new HashMap<String, Serializable>();
                boolean runConcurrently = true;
                final Runnable cleanupDeletedNodesJob = new Runnable() {
                    public void run() {
                        deleteNodes("/root/path/to/search/in");
                    }
                };
                try {
                    this.scheduler.addJob(cleanupDeletedNodes, cleanupDeletedNodesJob, cleanupDeletedNodesConfig, scheduleExp, runConcurrently);
                }
                catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
    
    private void deleteNodes(String searchRoot)
    {
        if (session != null && builder != null) {
            
            Map<String, String> map = new HashMap<String, String>();
            map.put("path", searchRoot);
            map.put("property", "@deleted");   // the node flagged to be deleted
            map.put("property.value", "yes");  // deleted property value = yes
            
            // create the actual query object.
            Query query = builder.createQuery(PredicateGroup.create(map), session);

            // perform search.
            SearchResult result = query.getResult();
            Iterator<Node> resultIter = result.getNodes();
            
            while (resultIter.hasNext()) {
                Node node = (Node) resultIter.next();
                try {
                    if (node.getName().equals(JcrConstants.JCR_CONTENT)) {
                        jcrRecursiveRemove.removeRecursive(node.getParent(), 0);
                    }
                    else {
                        jcrRecursiveRemove.removeRecursive(node, 0);
                    }
                }
                catch (RepositoryException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
}