RSS

How to create scheduler in portlet

Version Liferay-5.2.3
Using Liferay SDK, create a scheduler job in a portlet.

First create a class that contains actual task that needs to be executed:

package com.portlet;

import com.liferay.portal.kernel.job.IntervalJob;
import com.liferay.portal.kernel.job.JobExecutionContext;
import com.liferay.portal.kernel.job.JobExecutionException;
import com.liferay.portal.kernel.util.Time;


public class SyncDataJob implements IntervalJob{
 public SyncDataJob() {
  _interval = Time.DAY;
 }
 public long getInterval() {
  return _interval;
 }
 public void execute(JobExecutionContext context)
  throws JobExecutionException {
  try {
   System.out.println("THIS IS THE ACTUAL TASK!");
  }
  catch (Exception e) {
  }
 }
 private long _interval;
}

Second write a class that implements Scheduler interface.

package com.portlet.struts;

import com.portlet.SyncDataJob;
import com.liferay.portal.kernel.job.JobSchedulerUtil;
import com.liferay.portal.kernel.job.Scheduler;

public class EventHistoricoAction implements Scheduler {

 public void schedule() {

  JobSchedulerUtil.schedule(_testIntervalJob);
 }

 public void unschedule() {

  JobSchedulerUtil.unschedule(_testIntervalJob);
 }


 private SyncDataJob _testIntervalJob = new SyncDataJob();

}

Last just register your scheduler in liferay-portlet.xml

<liferay-portlet-app>
    <portlet>
        <portlet-name>eventosSearch-portlet</portlet-name>
        <scheduler-class>com.portlet.struts.EventHistoricoAction</scheduler-class>
    </portlet>
    <role-mapper>
        <role-name>administrator</role-name>
        <role-link>Administrator</role-link>
    </role-mapper>
</liferay-portlet-app>