Skip to content

Instantly share code, notes, and snippets.

@jmiranda
Last active April 28, 2016 15:25
Show Gist options
  • Save jmiranda/45084eb32f07f6e3d1934547cd4fbb9f to your computer and use it in GitHub Desktop.
Save jmiranda/45084eb32f07f6e3d1934547cd4fbb9f to your computer and use it in GitHub Desktop.
Overrides the default persistence context listener
package com.company
import grails.plugin.quartz2.PersistenceContextJobListener
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.codehaus.groovy.grails.support.PersistenceContextInterceptor
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyJobListener extends PersistenceContextJobListener {
private static final transient Log log = LogFactory.getLog(MyJobListener.class);
public static final String LISTENER_NAME = "myJobListener";
PersistenceContextInterceptor persistenceInterceptor
public static final transient String PERSITENCE_INIT = "gormSession";
@Override
public String getName() {
return LISTENER_NAME; //must return a name
}
@Override
public void jobToBeExecuted(JobExecutionContext context) {
if( isInitPersistenceContext(context) ){
persistenceInterceptor.init()
}
}
@Override
public void jobExecutionVetoed(JobExecutionContext context) { }
@Override
public void jobWasExecuted(JobExecutionContext context,
JobExecutionException jobException) {
// If the persistence interceptor exists and the job enabled gormSession
if(persistenceInterceptor && isInitPersistenceContext(context) ){
try {
persistenceInterceptor.flush()
persistenceInterceptor.clear()
} catch (Exception e) {
log.error("Exception occurred while flushing persistence context for job ${context.jobDetail.key}: " + e.message, e)
} finally {
try {
persistenceInterceptor.destroy()
} catch (Exception e) {
log.error("Exception occurred while destroying persistence context for job ${context.jobDetail.key}: " + e.message, e)
}
}
}
}
boolean isInitPersistenceContext(context){
if(context.mergedJobDataMap.containsKey(PERSITENCE_INIT) && context.mergedJobDataMap.get(PERSITENCE_INIT) == false){
return false
} else{
return true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment