
The goal of this tutorial is to create a scheduler in Liferay 7. Results of tasks will be used in wide variety of applications - data annotation, multimedia, sentiment analysis and search engine result evaluation.
You need to create a Liferay module project in eclipse IDE.
1. Create scheduler class:
Create a new class in your module named EmailSchedulear and add the cron expression
package com.themeray.emailschedulear.schedulear;
import com.liferay.portal.kernel.messaging.BaseMessageListener;
import com.liferay.portal.kernel.messaging.Message;
import org.osgi.service.component.annotations.Component;
@Component(
immediate = true,
property = {
"cron.expression= 0 0/05 1/1 1/1 * ?" // scheduler runs every 5 min.
},
service = EmailSchedulear.class
)
public class EmailSchedulear extends BaseMessageListener {
@Override
protected void doReceive(Message message) throws Exception {
// TODO Auto-generated method stub
}
}
In this Class you can specify your cron expression in ‘cron.expression’ property. Cron expressions are based on the timezone of your server. More about corn expression here https://www.freeformatter.com/cron-expression-generator-quartz.html
2. Override the doReceive method in your scheduler class:
This method will be called periodically based on your cron expression. You can write your business logic here which you want to execute periodically. i.e. you can write email sending and newsletter sending code here.
@Override
protected void doReceive(Message message) throws Exception {
log.info("Scheduled task executed...");
}
3. Register The scheduler:
@Activate
@Modified
protected void activate(Map<String, Object> properties) throws SchedulerException {
try {
String cronExpression = GetterUtil.getString(properties.get("cron.expression"), "cronExpression");
log.info(" cronExpression: " + cronExpression);
String listenerClass = getClass().getName();
Trigger jobTrigger = TriggerFactoryUtil.createTrigger(listenerClass, listenerClass, new Date(), null, cronExpression);
SchedulerEntryImpl schedulerEntryImpl = new SchedulerEntryImpl();
schedulerEntryImpl.setEventListenerClass(listenerClass);
schedulerEntryImpl.setTrigger(jobTrigger);
SchedulerEngineHelperUtil.register(this, schedulerEntryImpl, DestinationNames.SCHEDULER_DISPATCH);
} catch (Exception e) {
log.error(e);
}
}
4. Deactivate the scheduler:
@Deactivate
protected void deactive() {
SchedulerEngineHelperUtil.unregister(this);
}
