---
title: "Spring Quartz Batch"
author: "virusfu"
date: "2011-07-15T15:18:29Z"
tags: []
categories: ["编程语言"]
slug: "spring-quartz-batch"
draft: false
lastmod: "2011-07-15T15:18:29Z"
id: 1125303
url: "https://virusfu.iteye.com/blog/1125303"
---

**WEB-INF\\web.xml**

 &lt;context-param&gt;  
  &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
  &lt;param-value&gt;  
   **classpath:/job-bean.xml**  
  &lt;/param-value&gt;  
 &lt;/context-param&gt;

 &lt;listener&gt;  
  &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;  
 &lt;/listener&gt;

**WEB-INF\\classes\\job-bean.xml**

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;beans ...&gt;

 &lt;import resource="classpath:simple-job-launcher-context.xml"/&gt;  
 &lt;import resource="classpath:myHelloJob.xml"/&gt;  
   
 &lt;bean id="helloJob" class="org.springframework.scheduling.quartz.JobDetailBean"&gt;  
  &lt;property name="jobClass" value="quartz.example.HelloJob" /&gt;  
  &lt;property name="jobDataAsMap"&gt;  
   &lt;map&gt;  
    &lt;entry key="launcher" value-ref="jobLauncher"/&gt;  
    &lt;entry key="job" value-ref="myHelloJob"/&gt;  
   &lt;/map&gt;  
  &lt;/property&gt;  
 &lt;/bean&gt;

 &lt;bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"&gt;  
  &lt;property name="jobDetail" ref="helloJob" /&gt;  
  &lt;property name="startDelay" value="10000" /&gt;  
  &lt;property name="repeatInterval" value="50000" /&gt;  
 &lt;/bean&gt;  
   
 &lt;bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"&gt;  
  &lt;property name="triggers"&gt;  
   &lt;list&gt;  
    &lt;ref bean="simpleTrigger"/&gt;  
   &lt;/list&gt;  
  &lt;/property&gt;  
 &lt;/bean&gt;  
&lt;/beans&gt;

**WEB-INF\\classes\\simple-job-launcher-context.xml**

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;beans ...&gt;

 &lt;import resource="classpath:data-source-context.xml"/&gt;

 &lt;bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"&gt;  
  &lt;property name="databaseType" value="MYSQL" /&gt;   
  &lt;property name="dataSource" ref="dataSource" /&gt;  
  &lt;property name="transactionManager" ref="transctionManager" /&gt;   
 &lt;/bean&gt;

 &lt;bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher"&gt;  
  &lt;property name="jobRepository" ref="jobRepository" /&gt;  
 &lt;/bean&gt;

 &lt;bean id="simpleJob" class="org.springframework.batch.core.job.SimpleJob" abstract="true"&gt;  
  &lt;property name="jobRepository" ref="jobRepository" /&gt;  
 &lt;/bean&gt;

 &lt;bean id="taskletStep" class="org.springframework.batch.core.step.tasklet.TaskletStep" abstract="true"&gt;  
  &lt;property name="jobRepository" ref="jobRepository" /&gt;  
  &lt;property name="transactionManager" ref="transctionManager" /&gt;   
 &lt;/bean&gt;

&lt;/beans&gt;

**WEB-INF\\classes\\data-source-context.xml**

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;beans ...&gt;

 &lt;import resource="classpath:data-source-context-init.xml"/&gt;

 &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;  
  &lt;property name="driverClassName" value="org.gjt.mm.mysql.Driver"&gt;&lt;/property&gt;  
  &lt;property name="url" value="jdbc:mysql://127.0.0.1:5141/batch"&gt;&lt;/property&gt;  
  &lt;property name="username" value="sa"&gt;&lt;/property&gt;  
  &lt;property name="password" value="sqldba"&gt;&lt;/property&gt;  
 &lt;/bean&gt;

 &lt;bean id="transctionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
  lazy-init="true"&gt;  
  &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt;  
 &lt;/bean&gt;

&lt;/beans&gt;

**WEB-INF\\classes\\data-source-context-init.xml**

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;beans ...&gt;

 &lt;bean id="initializingFactoryBean" class="quartz.example.InitializingDataSourceFactoryBean"&gt;  
  &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt;  
  &lt;property name="initScript"&gt;  
   &lt;value&gt;classpath:schema-mysql.sql&lt;/value&gt;  
  &lt;/property&gt;  
 &lt;/bean&gt;  
   
&lt;/beans&gt;

**WEB-INF\\classes\\myHelloJob.xml**

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;beans ...&gt;

 &lt;bean id="myHelloJob" parent="simpleJob"&gt;  
  &lt;property name="name" value="myHelloJob" /&gt;  
  &lt;property name="steps"&gt;  
   &lt;list&gt;  
    &lt;bean id="firstHello" parent="taskletStep"&gt;  
     &lt;property name="tasklet"&gt;  
      &lt;bean class="quartz.example.MyHello"&gt;  
       &lt;property name="message" value="Hi~" /&gt;  
      &lt;/bean&gt;  
     &lt;/property&gt;  
    &lt;/bean&gt;  
   &lt;/list&gt;  
  &lt;/property&gt;  
 &lt;/bean&gt;  
   
&lt;/beans&gt;

**package quartz.example;**

public class InitializingDataSourceFactoryBean extends AbstractFactoryBean {

 private Resource initScript;  
 private Resource destroyScript;  
 DataSource dataSource;

 protected Object createInstance() throws Exception {  
    
  Assert.notNull(dataSource);  
  try {  
   doExecuteScript(destroyScript);  
  }  
  catch (Exception e) {  
   logger.debug("Could not execute destroy script \[" + destroyScript + "]", e);  
  }  
  doExecuteScript(initScript);  
  return dataSource;  
 }

 private void doExecuteScript(final Resource scriptResource) {  
    
  try {  
    
   if (scriptResource == null || !scriptResource.exists())  
    return;  
   TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));  
   if (initScript != null) {  
    transactionTemplate.execute(new TransactionCallback() {

     public Object doInTransaction(TransactionStatus status) {  
      JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);  
      String\[] scripts;  
      try {  
       scripts = StringUtils.delimitedListToStringArray(stripComments(IOUtils.readLines(scriptResource  
         .getInputStream())), ";");  
      }  
      catch (IOException e) {  
       throw new BeanInitializationException("Cannot load script from \[" + initScript + "]", e);  
      }  
      for (int i = 0; i &lt; scripts.length; i++) {  
       String script = scripts\[i].trim();  
       if (StringUtils.hasText(script)) {  
        jdbcTemplate.execute(scripts\[i]);  
       }  
      }  
      return null;  
     }

    });

   }  
  } catch (Exception e) {  
   logger.debug("기존에 스키마가 생성된 경우 오류가 발생 할 수 있으며, 오류 발생시 무시", e);  
  }  
 }

 private String stripComments(List list) {  
  StringBuffer buffer = new StringBuffer();  
  for (Iterator iter = list.iterator(); iter.hasNext();) {  
   String line = (String) iter.next();  
   if (!line.startsWith("//") && !line.startsWith("--")) {  
    buffer.append(line + "\\n");  
   }  
  }  
  return buffer.toString();  
 }

**package quartz.example;**

import org.springframework.batch.core.StepContribution;  
import org.springframework.batch.core.scope.context.ChunkContext;  
import org.springframework.batch.core.step.tasklet.Tasklet;  
import org.springframework.batch.repeat.RepeatStatus;  
import org.springframework.beans.factory.InitializingBean;

public class MyHello implements InitializingBean, Tasklet {  
   
 private static Log \_log = LogFactory.getLog(MyHello.class);  
   
 private String message = "";  
   
 public void setMessage(String message) {  
  this.message = message;  
 }

 @Override  
 public void afterPropertiesSet() throws Exception {  
  \_log.info("========= " + this.getClass().getSimpleName() + "=============" + message);  
 }

 @Override  
 public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {  
  \_log.info("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; " + this.getClass().getSimpleName() + "=====" + message );  
    
  return RepeatStatus.FINISHED;  
 }

}

**package quartz.example;**

import java.util.Date;  
import java.util.Iterator;

import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;  
import org.quartz.JobExecutionContext;  
import org.springframework.batch.core.Job;  
import org.springframework.batch.core.JobExecution;  
import org.springframework.batch.core.JobParameters;  
import org.springframework.batch.core.JobParametersBuilder;  
import org.springframework.batch.core.StepExecution;  
import org.springframework.batch.core.launch.JobLauncher;  
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;  
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;  
import org.springframework.batch.core.repository.JobRestartException;  
import org.springframework.scheduling.quartz.QuartzJobBean;

//public class HelloJob implements Job {  
public class HelloJob extends QuartzJobBean {

  private static Log \_log = LogFactory.getLog(HelloJob.class);  
      
  private JobLauncher launcher;  
  private Job job;  
      
  private int count = 0;  
      
  public void setLauncher(JobLauncher launcher) {  
    this.launcher = launcher;  
  }

  public void setJob(Job job) {  
    this.job = job;  
  }

  public HelloJob() {  
  }  
      
  protected void executeInternal(JobExecutionContext context) {  
    \_log.info("&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; " +  " Hello World! - " + new Date() + " &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;");  
       
    System.out.println("aaaa");  
       
    JobParametersBuilder jobParameterBulider = new JobParametersBuilder();  
    jobParameterBulider.addDate("date", new Date());  
       
    try {  
      JobExecution jobExecution = launcher.run(job, jobParameterBulider.toJobParameters());  
     
      for(Iterator&lt;StepExecution&gt; iterator =   
        jobExecution.getStepExecutions().iterator(); iterator.hasNext();) {  
          StepExecution stepExecution = iterator.next();  
        }  
    } catch (JobExecutionAlreadyRunningException e) {  
      e.printStackTrace();  
    } catch (JobRestartException e) {  
      e.printStackTrace();  
    } catch (JobInstanceAlreadyCompleteException e) {  
      e.printStackTrace();  
    }  
  }  
}