Created
November 29, 2015 23:27
-
-
Save seropian/a0db11c0460cc60f0ff5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.quartz.Job; | |
import org.quartz.JobExecutionContext; | |
import org.quartz.Scheduler; | |
import org.springframework.beans.BeanWrapper; | |
import org.springframework.beans.BeansException; | |
import org.springframework.beans.MutablePropertyValues; | |
import org.springframework.beans.PropertyAccessorFactory; | |
import org.springframework.context.ApplicationContext; | |
import org.springframework.context.ApplicationContextAware; | |
import java.lang.reflect.Method; | |
import java.util.Map; | |
public class ManualJobExecutor implements ApplicationContextAware { | |
private ApplicationContext applicationContext; | |
public void executeJob(final Class<Job> jobClass) { | |
try { | |
//create job instance | |
final Job quartzJob = jobClass.newInstance(); | |
// For the created job instance, search all services that are injected by quartz. | |
// Those service instances are kept inside each scheduler context as a map | |
final BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(quartzJob); | |
final MutablePropertyValues propertyValues = new MutablePropertyValues(); | |
//get all schedulers defined across all spring configurations for this application | |
final Map<String, Scheduler> schedulers = applicationContext.getBeansOfType(Scheduler.class); | |
for (final Scheduler scheduler : schedulers.values()) { | |
// Populate the possible properties with service instances found | |
propertyValues.addPropertyValues(scheduler.getContext()); | |
} | |
//set the properties of the job (injected wallet services) with the matching services | |
//the other services in the list that have no matching properties shall be ignored | |
beanWrapper.setPropertyValues(propertyValues, true); | |
//get method executeInternal(JobExecutionContext) from job class extending QuartzJobBean | |
final Method executeJobMethod = quartzJob.getClass().getDeclaredMethod("executeInternal", (JobExecutionContext.class)); | |
executeJobMethod.setAccessible(true); | |
//call the processItems method on the Job class instance | |
executeJobMethod.invoke(quartzJob); | |
} catch (final Exception e) { | |
throw new RuntimeException(String.format("Exception while retrieving and executing job for name=%s", jobClass.getName()), e); | |
} | |
} | |
@Override | |
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { | |
this.applicationContext = applicationContext; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment