728x90

출처 : Chapter 19. Quartz 혹은 Timer 를 사용한 스케쥴링     

DongHoReportBatch.java

package com.blueX.batch;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class DongHoReportBatch extends QuartzJobBean {

	@Override
	protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss a"); 
		System.out.println(sdf.format(dt).toString()); 
	}
	
	public static void main(String[] args) throws Exception {
		String[] configLocation = new String[] { "file:WebContent/WEB-INF/blueX-servlet.xml" };
		ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
	}

}

blueX-servlet.xml

	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" autowire="no">
		<property name="triggers">
       		<list>
	         	<ref bean="dongHoReportTrigger" />
			</list>
     	</property>
     	<property name="quartzProperties">
		    <props>
		    	<prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
		        <prop key="org.quartz.threadPool.threadCount">5</prop>
		        <prop key="org.quartz.threadPool.threadPriority">4</prop>
		        <prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>
		        <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>
			</props>
		</property>
	</bean>
	
	<bean id="dongHoReportTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
		<property name="jobDetail" ref="dongHoReportJob" />
		<property name="startDelay" value="60000"/> <!-- 서버 시작후 1분후 첫 실행 -->
		<property name="repeatInterval" value="300000"/> <!-- 첫 실행 후 5분 마다 실행 -->
	</bean> 
	
	<bean id="dongHoReportJob" class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.blueX.batch.DongHoReportBatch" />
	</bean>
728x90
728x90

package org.quartz.impl.jdbcjobstore;

public abstract class JobStoreSupport implements JobStore, Constants {

    class MisfireHandler extends Thread {
        public void run() {
            while (!shutdown) {

                RecoverMisfiredJobsResult recoverMisfiredJobsResult = manage();

                if (!shutdown) {
                    long timeToSleep = 50l;  // At least a short pause to help balance threads
                    if (!recoverMisfiredJobsResult.hasMoreMisfiredTriggers()) {
                        timeToSleep = getMisfireThreshold() - (System.currentTimeMillis() - sTime);
                        if(numFails > 0) {
                            timeToSleep = Math.max(getDbRetryInterval(), timeToSleep);
                        }
                    }
                    Thread.sleep(timeToSleep);
                }//while !shutdown
            }
        }

        private RecoverMisfiredJobsResult manage() {
            try {
                RecoverMisfiredJobsResult res = doRecoverMisfires();
            } catch (Exception e) {
            }
            return RecoverMisfiredJobsResult.NO_OP;
        }
    }

    protected RecoverMisfiredJobsResult doRecoverMisfires() throws JobPersistenceException {
        boolean transOwner = false;
        Connection conn = getNonManagedTXConnection();
        try {
            RecoverMisfiredJobsResult result = RecoverMisfiredJobsResult.NO_OP;
           
            // Before we make the potentially expensive call to acquire the
            // trigger lock, peek ahead to see if it is likely we would find
            // misfired triggers requiring recovery.
            int misfireCount = (getDoubleCheckLockMisfireHandler()) ?
                getDelegate().countMisfiredTriggersInStates(conn, STATE_MISFIRED, STATE_WAITING, getMisfireTime()) :
                Integer.MAX_VALUE;
           
            if (misfireCount == 0) {
                getLog().debug("Found 0 triggers that missed their scheduled fire-time.");
            } else {
                transOwner = getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS);
               
                result = recoverMisfiredJobs(conn, false);
            }
           
            commitConnection(conn);
            return result;
        } catch (JobPersistenceException e) {
        }
    }

    protected RecoverMisfiredJobsResult recoverMisfiredJobs(Connection conn, boolean recovering)
        throws JobPersistenceException, SQLException {

        // If recovering, we want to handle all of the misfired
        // triggers right away.
        int maxMisfiresToHandleAtATime =
            (recovering) ? -1 : getMaxMisfiresToHandleAtATime();
       
        List misfiredTriggers = new ArrayList();
        long earliestNewTime = Long.MAX_VALUE;
        // We must still look for the MISFIRED state in case triggers were left
        // in this state when upgrading to this version that does not support it.
        boolean hasMoreMisfiredTriggers =
            getDelegate().selectMisfiredTriggersInStates(
                conn, STATE_MISFIRED, STATE_WAITING, getMisfireTime(),
                maxMisfiresToHandleAtATime, misfiredTriggers);

        for (Iterator misfiredTriggerIter = misfiredTriggers.iterator(); misfiredTriggerIter.hasNext();) {
            Key triggerKey = (Key) misfiredTriggerIter.next();
           
            Trigger trig = retrieveTrigger(conn, triggerKey.getName(), triggerKey.getGroup());

            if (trig == null) {
                continue;
            }

            doUpdateOfMisfiredTrigger(conn, null, trig, false, STATE_WAITING, recovering);

            if(trig.getNextFireTime() != null && trig.getNextFireTime().getTime() < earliestNewTime)
             earliestNewTime = trig.getNextFireTime().getTime();
        }

        return new RecoverMisfiredJobsResult(
                hasMoreMisfiredTriggers, misfiredTriggers.size(), earliestNewTime);
    }

    protected Trigger retrieveTrigger(Connection conn, String triggerName, String groupName)
        throws JobPersistenceException {
        try {
            Trigger trigger = getDelegate().selectTrigger(conn, triggerName, groupName);
            if (trigger == null) {
                return null;
            }
           
            // In case Trigger was BLOB, clear out any listeners that might
            // have been serialized.
            trigger.clearAllTriggerListeners();
           
            String[] listeners = getDelegate().selectTriggerListeners(conn, triggerName, groupName);
            for (int i = 0; i < listeners.length; ++i) {
                trigger.addTriggerListener(listeners[i]);
            }

            return trigger;
        } catch (Exception e) {
            throw new JobPersistenceException("Couldn't retrieve trigger: " + e.getMessage(), e);
        }
    }
}

package org.quartz.impl.jdbcjobstore;

public class StdJDBCDelegate implements DriverDelegate, StdJDBCConstants {

    public boolean selectMisfiredTriggersInStates(Connection conn, String state1, String state2,

    String SELECT_MISFIRED_TRIGGERS_IN_STATES = "SELECT "
        + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + " FROM "
        + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE "
        + COL_NEXT_FIRE_TIME + " < ? "
        + "AND ((" + COL_TRIGGER_STATE + " = ?) OR (" + COL_TRIGGER_STATE + " = ?)) "
        + "ORDER BY " + COL_NEXT_FIRE_TIME + " ASC";        

    }

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

    String SELECT_TRIGGER = "SELECT *" + " FROM "
            + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE "
            + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?";

    String SELECT_CRON_TRIGGER = "SELECT *" + " FROM "
            + TABLE_PREFIX_SUBST + TABLE_CRON_TRIGGERS + " WHERE "
            + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?";

    }
}

728x90
728x90

출처 : 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 -

728x90
728x90

출처 : 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();
    }
  }
}

728x90
728x90

출처
http://whiteship.tistory.com/1516
http://blog.naver.com/an5asis/60019595888

Job - 이 인터페이스를 상속 받아서 execute 메소드를 구현해야 됩니다. (실행 수행되는 내용)
JobDetail - 
Trigger - 작업을 언제 실행할 지 정의합니다.
  SimpleTrigger - start time, end time, interval time, repeat times 등을 설정할 수 있습니다.
  CronTrigger - Linux의 cron 하고 비슷하게, 특정 시간이 되면 발동하게 해줍니다.
 
SchedulerFactory
  StdSchedulerFactory - 클래스패스에 quartz.properties 파일을 먹고 삽니다. 
    Scheduler - 스케쥴 팩토리에서 얻어 옵니다. JobDetail과 Trigger를 가지고 스케쥴을 정할 수 있습니다.

package QuartzApp;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloJob implements Job {

 @Override
 public void execute(JobExecutionContext arg0) throws JobExecutionException {
  System.out.println("HelloJob !!!");  
 }
}

package QuartzApp;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;

public class HelloJobTest1Main {

 public static void main(String[] args) {
   try {
     SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
     Scheduler sched = schedFact.getScheduler();
     sched.start();

     JobDetail jobDetail = new JobDetail("HelloJob", HelloJob.class);
     SimpleTrigger trigger = new SimpleTrigger("HelloJob");
     trigger.setRepeatInterval(1l);
     trigger.setRepeatCount(100);  // 100번 반복
     sched.scheduleJob(jobDetail, trigger);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
}

728x90

+ Recent posts