How to create scheduler in liferay portlet

Sometimes you have a need to create a task that is being executed periodically. You can use scheduler (based on Quartz API ) that is integrated with Liferay. There are 3 steps to do this.

1. Write a class the implements the com.liferay.portal.job.Scheduler interface

2. Write a class that contains actual task that needs to be executed. This class must implements com.liferay.portal.job.IntervalJob interface

3. Register your scheduler in liferay-portlet-ext.xml ( if you use ext environment )

Now let’s go to the details.

1. Write a class that implements Scheduler interface.

package com.ext.portlet.onlineproject.job;

import com.liferay.portal.job.JobScheduler;
import org.quartz.SchedulerException;

public class Scheduler implements com.liferay.portal.job.Scheduler {

	public void schedule() throws SchedulerException {
	JobScheduler.schedule(new SyncDataJob());
	}
}

2. Write the class that contains actual task. On this example, our actual task would be only to write ‘THIS IS THE ACTUAL TASK!” to console. This task would be executed every minute.

package com.ext.portlet.onlineproject.job;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.liferay.portal.job.IntervalJob;
import com.liferay.util.Time; 

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


If you want to change the interval, you can just change this line :

public SyncDataJob() {
_interval = Time.MINUTE;
}

Change Time.MINUTE to Time.HOUR or Time.DAY.

3. Register in liferay-portlet-ext.xml.

<portlet>
<portlet-name>Online_Project</portlet-name>
<struts-path>ext/onlineproject</struts-path>
<scheduler-class>com.ext.portlet.onlineproject.job.Scheduler</scheduler-class>
<use-default-template>false</use-default-template>
</portlet>

Done. ( This article tested on Liferay 4.3.3 )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值