Reputation: 5565
I am using Liferay 6.2 CE GA4. I have been trying to schedule the execution of a method in the controller of my portlet.
I came across many tutorials in which most of the tutorials provide cases where we could provide the time in liferay-portlet.xml, like this tutorial. But I would like to have the time configured by the user in the portal. So is it possible to get the time and implement a simple scheduling job in my constroller.
EDIT: I have a controller like following which does the scheduling job.
public class MyController {
@RenderMapping
public String defaultView() {
String cron = "0 0/1 * 1/1 * ? *";
Date dt = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.add(Calendar.MINUTE, 2);
Trigger trigger = null;
try {
trigger = TriggerFactoryUtil.buildTrigger(TriggerType.CRON, Scheduler.class.getName(), Scheduler.class.getName(), calendar.getTime(), calendar.getTime(), cron);
} catch (SchedulerException e) {
e.printStackTrace();
}
Portlet portlet = PortletLocalServiceUtil.getPortletById("portlet_id");
Message message = new Message();
message.put("CONTEXT_PATH", portlet.getContextPath());
message.put(SchedulerEngine.MESSAGE_LISTENER_CLASS_NAME, Scheduler.class.getName());
message.put(SchedulerEngine.PORTLET_ID, portlet.getPortletId());
Scheduler scheduler = new Scheduler();
MessageBusUtil.registerMessageListener(DestinationNames.SCHEDULER_DISPATCH, scheduler);
try {
SchedulerEngineHelperUtil.schedule( trigger, StorageType.PERSISTED, "", DestinationNames.SCHEDULER_DISPATCH, message, 5);
} catch (SchedulerException e) {
e.printStackTrace();
}
return "view";
}
}
The Scheduler
class above is defined as below.
public class Scheduler implements MessageListener {
@Override
public void receive(Message message) throws MessageListenerException {
myMethodAtScheduledTime();
}
public void myMethodAtScheduledTime() {
System.out.println("Invoked at " + new Date());
}
}
The method myMethodAtScheduledTime
is invoked every 10 or 20 seconds. How can I restrict the call to just once. i.e. exactly at the time calendar instance time + 2 min (calendar.add(Calendar.MINUTE, 2);
)
Upvotes: 1
Views: 1354
Reputation: 2862
The scheduler can be created dynamically.
MessageListener
- an interface with just one receive(Message)
method.SchedulerEngineHelperUtil#schedule
method. The trigger takes message listener class and invocation time as parameters (among others).See Creating the scheduler dynamically in liferay blog post or this forum post to find some examples.
Upvotes: 2