Search

'Spring Quartz'에 해당되는 글 2건

  1. 2010.09.17 Quartz Web Application (1)
  2. 2010.09.14 Spring Quartz Batch (2)

Quartz Web Application

Programming/Java 2010.09.17 10:18 Posted by 파란크리스마스

출처 : http://journae.springnote.com/pages/6100033



WEB-INF\web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="starter" version="2.4" ...>

 <context-param>
  <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
  <param-value>ApplicationResources</param-value>
 </context-param>

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
 </context-param>

 <context-param>
  <param-name>webAppRootKey</param-name>
  <param-value>quartz.root</param-value>
 </context-param>

 <context-param>
  <param-name>log4jConfigLocation</param-name>
  <param-value>classpath:log4j.xml</param-value>
 </context-param>

 <filter>
  <filter-name>action2-cleanup</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
 </filter>

 <filter>
  <filter-name>sitemesh</filter-name>
  <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
 </filter>

 <filter>
  <filter-name>sitemesh-freemarker</filter-name>
  <filter-class>org.apache.struts2.sitemesh.FreeMarkerPageFilter</filter-class>
 </filter>

 <filter>
  <filter-name>action2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>action2-cleanup</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>sitemesh-freemarker</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>action2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <!-- Listeners -->
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <listener>
  <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
 </listener>

 <servlet>
  <servlet-name>freemarker</servlet-name>
  <servlet-class>com.opensymphony.module.sitemesh.freemarker.FreemarkerDecoratorServlet</servlet-class>
 </servlet>

 <servlet>
  <servlet-name>DefinitionInitializer</servlet-name>
  <servlet-class>org.quartz.ui.web.init.DefinitionInitializer</servlet-class>
  <init-param>
   <param-name>definition-file</param-name>
   <param-value>(PATH_TO_DEFINITIONS_FILE)</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <!-- Servlets -->
 <servlet>
  <servlet-name>jspSupportServlet</servlet-name>
  <servlet-class>org.apache.struts2.views.JspSupportServlet</servlet-class>
  <load-on-startup>5</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>freemarker</servlet-name>
  <url-pattern>*.ftl</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 </web-app>

WEB-INF\classes\applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <bean id="authenticator" class="org.quartz.ui.web.security.SimpleAuthenticator">
  <property name="username">
   <value>quartz</value>
  </property>
  <property name="password">
   <value>quartz</value>
  </property>
 </bean>

 <bean id="logonAction" class="org.quartz.ui.web.action.LogonAction" scope="prototype">
  <property name="authenticator" ref="authenticator" />
 </bean>

 <bean id="quartzUser" class="org.quartz.ui.web.security.User">
  <property name="username"><value>quartz</value></property>
  <property name="password"><value>quartz</value></property>
  <property name="roles">
  <map>
   <entry key="manager">
    <value>manager</value>
   </entry>
  </map>
  </property>
 </bean>

 <bean id="users" class="org.quartz.ui.web.security.Users">
  <property name="userMap">
  <map>
   <entry key="quartz">
    <ref bean="quartzUser"/>
   </entry>
  </map>
  </property>
 </bean>

</beans>

WEB-INF\classes\quartz.properties

#============================================================================
# Configure Main Scheduler Properties 
#============================================================================

 
org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = AUTO
 
#============================================================================
# Configure ThreadPool 
#============================================================================

 
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
org.quartz.threadPool.threadPriority = 4
 
#============================================================================
# Configure JobStore 
#============================================================================

 
org.quartz.jobStore.misfireThreshold = 60000
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
##org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.oracle.OracleDelegate
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate

org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties = true
org.quartz.jobStore.dataSource=myDS
org.quartz.jobStore.tablePrefix = QRTZ_

org.quartz.jobStore.isClustered= true
org.quartz.jobStore.clusterCheckinInterval= 20000
 
#============================================================================
# Configure Datasources 
#============================================================================


org.quartz.dataSource.myDS.driver=com.mysql.jdbc.Driver
org.quartz.dataSource.myDS.URL=jdbc:mysql://localhost:5141/batch
org.quartz.dataSource.myDS.user=root
org.quartz.dataSource.myDS.password=

#org.quartz.dataSource.myDS.driver = oracle.jdbc.driver.OracleDriver
#org.quartz.dataSource.myDS.URL = jdbc:oracle:thin:@polarbear:1521:dev
#org.quartz.dataSource.myDS.user = quartz
#org.quartz.dataSource.myDS.password = quartz
#org.quartz.dataSource.myDS.maxConnections = 5

 
#org.quartz.dataSource.myDS.driver = org.postgresql.Driver
#org.quartz.dataSource.myDS.URL = jdbc:postgresql:dev
#org.quartz.dataSource.myDS.user = jhouse
#org.quartz.dataSource.myDS.password =
#org.quartz.dataSource.myDS.maxConnections = 5

 
#============================================================================
# Configure Plugins
#============================================================================

 
#*  org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin

#*  org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
#*  # init plugin will load jobs.xml as a classpath resource i.e. /jobs.xml if not found on file system
#*  org.quartz.plugin.jobInitializer.fileNames=jobs.xml
#*  org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
#*  org.quartz.plugin.jobInitializer.failOnFileNotFound = false
#*  org.quartz.plugin.jobInitializer.scanInterval = 30
#*  # org.quartz.plugin.jobInitializer.wrapInUserTransaction = true

#*  org.quartz.plugin.jobInitializerMultiple.class = org.quartz.plugins.xml.JobInitializationPlugin
#*  # init plugin will load jobs.xml as a classpath resource i.e. /jobs.xml and jobs2.xml if not found on file system
#*  org.quartz.plugin.jobInitializerMultiple.fileNames=jobs2.xml,jobs3.xml
#*  org.quartz.plugin.jobInitializerMultiple.overWriteExistingJobs = false
#*  org.quartz.plugin.jobInitializerMultiple.failOnFileNotFound = false
#*  # org.quartz.plugin.jobInitializerMultiple.wrapInUserTransaction = true

quartz.properties 환경 파일 로딩 순서

org.quartz.ui.web.init.DefinitionInitializer.init
  |
  org.quartz.ee.servlet.QuartzInitializerServlet.init
    |
    org.quartz.impl.StdSchedulerFactory.getScheduler
      |
      org.quartz.impl.StdSchedulerFactory
        initialize() 메소드에서 quartz.properties 파일 로딩

DB의 설정된 Job을 조회 하여 등록하는 순서

org.quartz.simpl.SimpleThreadPool$WorkerThread.run
  |
  org.quartz.core.JobRunShell.run
    |
    org.quartz.jobs.FileScanJob.execute
      |
      org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger
        |
        org.quartz.impl.jdbcjobstore.StdJDBCDelegate.selectTrigger

StdJDBCDelegate의 selectTrigger 메소드

package org.quartz.impl.jdbcjobstore;

public class StdJDBCDelegate implements DriverDelegate, StdJDBCConstants {

    public Trigger selectTrigger(Connection conn, String triggerName,
            String groupName) throws SQLException, ClassNotFoundException,
            IOException {

        try {
            Trigger trigger = null;

            ps = conn.prepareStatement(rtp(SELECT_TRIGGER));
            rs = ps.executeQuery();

                if (triggerType.equals(TTYPE_SIMPLE)) {
                    ps = conn.prepareStatement(rtp(SELECT_SIMPLE_TRIGGER));

                    if (rs.next()) {
                        SimpleTrigger st = new SimpleTrigger(triggerName,
                                groupName, jobName, jobGroup, startTimeD,
                                endTimeD, repeatCount, repeatInterval);

                        if (null != map) {
                            st.setJobDataMap(new JobDataMap(map));
                        }
                        trigger = st;
                    }
                } else if (triggerType.equals(TTYPE_CRON)) {
                    ps = conn.prepareStatement(rtp(SELECT_CRON_TRIGGER));

                    CronTrigger ct = new CronTrigger(triggerName, groupName,
                                    jobName, jobGroup, startTimeD, endTimeD,
                                    cronExpr, timeZone);
                    if (null != map) {
                        ct.setJobDataMap(new JobDataMap(map));
                    }
                    trigger = ct;

                } else if (triggerType.equals(TTYPE_BLOB)) {
                    ....
                } else {
                    throw new ClassNotFoundException("class for trigger type '"
                            + triggerType + "' not found.");
                }
            }

            return trigger;
        } finally {
            closeResultSet(rs);
            closeStatement(ps);
        }
    }

Cluster 관련 내용

org.quartz.impl.jdbcjobstore.JobStoreSupport

public abstract class JobStoreSupport implements JobStore, Constants {

    protected boolean doCheckin() throws JobPersistenceException {
        failedRecords = clusterCheckIn(conn);
    }

    class ClusterManager extends Thread {
        private boolean manage() {
            res = doCheckin();
            return res;
        }

        public void run() {
            while (!shutdown) {

                if (!shutdown) {
                    long timeToSleep = getClusterCheckinInterval();
                    timeToSleep = Math.max(getDbRetryInterval(), timeToSleep);
                    Thread.sleep(timeToSleep);
                    this.manage()) {
                }

            }//while !shutdown
        }
    }
}

- end -

신고

Spring Quartz Batch

Programming/Java 2010.09.14 16:31 Posted by 파란크리스마스

출처 : http://wiki.dev.daewoobrenic.co.kr/mediawiki/index.php/Spring_Quartz_Batch

WEB-INF\web.xml

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   classpath:/job-bean.xml
  </param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

WEB-INF\classes\job-bean.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

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

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

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

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <import resource="classpath:data-source-context.xml"/>

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

 <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
  <property name="jobRepository" ref="jobRepository" />
 </bean>

 <bean id="simpleJob" class="org.springframework.batch.core.job.SimpleJob" abstract="true">
  <property name="jobRepository" ref="jobRepository" />
 </bean>

 <bean id="taskletStep" class="org.springframework.batch.core.step.tasklet.TaskletStep" abstract="true">
  <property name="jobRepository" ref="jobRepository" />
  <property name="transactionManager" ref="transctionManager" />
 </bean>

</beans>

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

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <import resource="classpath:data-source-context-init.xml"/>

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

 <bean id="transctionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
  lazy-init="true">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

</beans>

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

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

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

WEB-INF\classes\myHelloJob.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

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

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 < 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(">>>>>>>>>>> " + 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("<<<<<<<< " +  " Hello World! - " + new Date() + " >>>>>>>>");
     
    System.out.println("aaaa");
     
    JobParametersBuilder jobParameterBulider = new JobParametersBuilder();
    jobParameterBulider.addDate("date", new Date());
     
    try {
      JobExecution jobExecution = launcher.run(job, jobParameterBulider.toJobParameters());
   
      for(Iterator<StepExecution> 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();
    }
  }
}

신고


 

티스토리 툴바