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 )
本文介绍如何在Liferay中使用基于Quartz API的调度器来创建周期性执行的任务。通过实现特定接口并配置XML文件,可以轻松地设定定时任务。
3797

被折叠的 条评论
为什么被折叠?



