由于项目将要上线,而项目中的Quartz集群配置一直没时间弄,本以为应该是一件挺简单的事,没想到Gooble了一两天才解决问题,主要是因为Spring到3.0.7这个版本为止都没有原生支持Quartz的集群,原来的Quartz配置在单实例下运行正常,配置集群之后各种异常都来了,今天终于配置成功,在这里做一个笔记,避免以后走弯路。
这里要先感谢一下 http://www.linuxidc.com/Linux/2012-06/63408.htm 的博主,在参考了此博客后才得以成功。
首先是任务Bean,可以是一个普通的Service或者Bean
- @Service("helloJob")
- public HelloServiceImpl implements HelloService{
- @Autowired
- private HelloDao dao;
- public void executeJob(){
- List list = dao.findJob();
- // TODO:这里实现自己的功能
- }
- }
第二步创建一个任务代理类DetailQuartzJobBean
- public class DetailQuartzJobBean extends QuartzJobBean implements ApplicationContextAware {
- protected final Log logger = LogFactory.getLog(getClass());
- private String targetObject;
- private String targetMethod;
- private ApplicationContext ctx;
- protected void executeInternal(JobExecutionContext context)
- throws JobExecutionException {
- try {
- logger.info("execute [" + targetObject + "] at once>>>>>>");
- Object otargetObject = ctx.getBean(targetObject);
- Method m = null;
- try {
- m = otargetObject.getClass().getMethod(targetMethod,new Class[] {});
- m.invoke(otargetObject, new Object[] {});
- } catch (SecurityException e) {
- logger.error(e);
- } catch (NoSuchMethodException e) {
- logger.error(e);
- }
- } catch (Exception e) {
- throw new JobExecutionException(e);
- }
- }
- public void setApplicationContext(ApplicationContext applicationContext){
- this.ctx=applicationContext;
- }
- public void setTargetObject(String targetObject) {
- this.targetObject = targetObject;
- }
- public void setTargetMethod(String targetMethod) {
- this.targetMethod = targetMethod;
- }
- }
这个类是调用Job service的关键
