Sunday, 21 June 2015

How to implement cron job/scheduler in Liferay custom portlet

Many a times people like to execute specific job on a particular time interval. Liferay provides support for same.

There are three simple steps availbale to do same:

1)  Add entry inside liferay-portlet.xml file
2)  Write class which will be triggered on a specific time interval
3)  Redeploy your portlet and verify

Here are the detailed steps:

1)  Add entry inside liferay-portlet.xml file

    Here is the quick reference of liferay-portlet.xml file

<scheduler-entry>
<scheduler-description>Student Result</scheduler-description>
<scheduler-event-listener-class>com.test.PublishResult</scheduler-event-listener-class>
<trigger>
<cron>
<cron-trigger-value>0 0/5 * 1/1 * ? *</cron-trigger-value>
</cron>
</trigger>
</scheduler-entry>

In above code

"<scheduler-event-listener-class>" is the class name whose "receive" method will be triggered as and when the "<cron-trigger-value>" event occurs.
"<cron-trigger-value>" will be triggered every five minutes.



2)  Write class which will be triggered on a specific time interval

Here is the sample class entry which we specified inside liferay-portlet.xml file under "<scheduler-event-listener-class>"

package com.test;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.portal.kernel.util.StringPool;

public class PublishResult implements MessageListener{

private static final Log LOGGER = LogFactoryUtil.getLog(PublishResult.class);

@Override
public void receive(Message message) throws MessageListenerException {
// TODO Auto-generated method stub
//System.out.println("Student Result Published");
LOGGER.info("Published Result");
}

}

3)  Redeploy your portlet and verify

    To see the LOGGER.info statement inside catalina.out, you need to redeploy your portlet.
    Wait for five minutes and you will see a statement like this in output.
   
    "06:40:02,421 INFO  [PublishResult:20] Published Result"
   

Cheers! You are done.

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics

No comments:

Post a Comment