Wednesday, November 19, 2008

Revisited: Spring InvervalJobs and scheduling in Liferay 5

Update to a better way to go about Spring scheduling: I tried simply defining a destroy method on the scheduler bean instead of relying on the extended ContextLoaderListener. This never appeared to be invoked and subsequently didn't unschedule the jobs. This is quite problematic in the long-run. Not good to have duplicate jobs running at the same time, it's sloppy and bad things could happen. So simply having the destroy method was insufficient.

Instead of extending Liferay's JobScheduler (as I suggested in the previous post), it made more sense to create a singleton POJO that then invokes com.liferay.portal.kernel.job.JobSchedulerUtil.getJobScheduler().schedule(). That way the dependency is relying on Liferay's Quartz integration altogether (not thinking any of this would ever live outside of Liferay, but in the event that it does should be able to propagate that dependency with minor adjustments). Everything said and done (and tested), this is the scheduler:


public class JobScheduler {
private static Log _log = LogFactory.getLog(JobScheduler.class);
public Set jobs = new HashSet();

/**
* Set all of the scheduled jobs.
*
* @param jobs Set of jobs to schedule.
*/
public void setJobs(Set jobs) {
this.jobs = jobs;
}

public void init(){
com.liferay.portal.kernel.job.JobScheduler scheduler = JobSchedulerUtil.getJobScheduler();

for(IntervalJob job : jobs){
try {
_log.info("Initializating " + job);
scheduler.schedule(job);
}
catch (Exception e) {
_log.error("Initialization error instantiating " +job);
_log.error(e);
}
}
}

public void destroy() {
com.liferay.portal.kernel.job.JobScheduler scheduler = JobSchedulerUtil.getJobScheduler();

for(IntervalJob job : jobs){
try {
_log.info("Unscheduling " + job);
scheduler.unschedule(job);
}
catch (Exception e) {
_log.error("Unscheduling error with" +job);
_log.error(e);
}
}
}
}

No comments: