Introduction
Liferay provides an easy way to implement scheduler. Scheduler is a very important aspect of software development these days. Using Liferay Scheduler we can automate certain processes and execute it on every specified time interval. i.e send an email after every day, send monthly newsletters, etc.
Prerequisites
- JDK 8
- Liferay portal 7/7.x
Assuming that you have already created a Liferay module project in eclipse IDE.
1) Create scheduler class
@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 {
}
Here, you can specify your cron expression in ‘cron.expression’ property.
Cron expressions are based on the timezone of your server. You can learn 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 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);
}