2/08/2011

How to create a Scheduled Job in Liferay 6

If you want to have a cron job, a scheduled task or a scheduled task in Liferay 6, you can do the following:


Note, that all of this takes place in your portlet - no need to go for the ext environment.


Create the class that contains your business code


Implement the MessageListener interface and put your business code into the "receive" method.
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
public class TestJob implements MessageListener {
@Override
 public void receive(Message arg0) throws MessageListenerException {
 System.out.println("doing important work ...");
}}


Configure Your Portlet


Your Portlet needs to have the configuration for the TestJob. This can be done by adding the following to your liferay-portlet.xml:

<portlet-name>JobTestPorftlet</portlet-name><icon>/icon.png</icon>
<scheduler-entry>
  <scheduler-description>description</scheduler-description>
  <scheduler-event-listener-class>
    de.test.TestJob
  </scheduler-event-listener-class>
  <trigger>
    <cron>
      <cron-trigger-value>59 23 * * 0 ?</cron-trigger-value>
    </cron>
  </trigger>
</scheduler-entry>


This will run your job once a week sundays at 23:59. If you want the simple approach you can replace the cron time by this:

<simple>
  <simple-trigger-value>1</simple-trigger-value>
  <time-unit>minute</time-unit>
</simple>

This will run your job once the server is started and then every minute.


If you liked this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.