[SPRING] Java 예제 : Quartz를 사용한 동적 작업 스케줄링
SPRINGJava 예제 : Quartz를 사용한 동적 작업 스케줄링
Quartz JOB을 동적으로 정의하기 위해 사용자 인터페이스를 노출하고 싶다. 사용자가 JOB 이름, cron 표현식 또는 시간 간격, 작업에 대한 특정 Java 클래스 등의 JOB 속성을 정의 할 수있는 기능이 있어야하는 곳
이 기능을 용이하게하는 오픈 소스가 있습니까? 또는 동적 Quartz Scheduler 용 모듈을 직접 만들고 싶다면 어떻게해야할까요?
해결법
-
==============================
1.동적 석영 작업 스케줄링을위한 예제 코드 :
동적 석영 작업 스케줄링을위한 예제 코드 :
Maven 종속성
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>1.8.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency>
응용 프로그램 컨텍스트 파일 (dynamic-jobs.xml)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"> <!-- The Task Bean--> <bean id="myTask" class="com.xxx.example.dynamicjob.MyTask" /> <!-- The quartz scheduler configuration --> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"/> </beans>
태스크를위한 Java 클래스
package com.xxx.example.dynamicjob; public class MyTask { public void performAction() { System.out.println("Hey, you reached me...:)"); } }
동적 작업을 생성하는 Java 클래스
package com.xxx.example.dynamicjob; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.scheduling.quartz.CronTriggerBean; import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean; public class DynamicJobExample { /** * @param args */ public static void main(String[] args) { ClassPathResource res = new ClassPathResource("dynamic-jobs.xml"); XmlBeanFactory factory = new XmlBeanFactory(res); //get the quartzFactory bean Scheduler scheduler = (Scheduler) factory.getBean("scheduler"); //get the task bean MyTask myTask = (MyTask) factory.getBean("myTask"); try { // create JOB MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean(); jobDetail.setTargetObject(myTask); jobDetail.setTargetMethod("performAction"); jobDetail.setName("MyJobDetail"); jobDetail.setConcurrent(false); jobDetail.afterPropertiesSet(); /* SimpleTriggerBean trigger = new SimpleTriggerBean(); trigger.setBeanName("MyTrigger"); trigger.setJobDetail((JobDetail) jobDetail.getObject()); trigger.setRepeatInterval(5000); trigger.afterPropertiesSet(); */ // create CRON Trigger CronTriggerBean cronTrigger = new CronTriggerBean(); cronTrigger.setBeanName("CRON0001"); // Execute after each 5 second String expression = "5 * * * * ?"; cronTrigger.setCronExpression(expression); cronTrigger.afterPropertiesSet(); //scheduler.scheduleJob(jobDetail, cronTrigger); scheduler.scheduleJob((JobDetail) jobDetail.getObject(), cronTrigger); // Start Scheduler scheduler.start(); } catch (Exception e) { e.printStackTrace(); } } }
-
==============================
2.Spring 4는 아무런 문제없이 이것을 할 수있게 해준다. (Quartz 2.0) - spring-dispatcher-servlet.xml
Spring 4는 아무런 문제없이 이것을 할 수있게 해준다. (Quartz 2.0) - spring-dispatcher-servlet.xml
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/> <task:scheduler id="myScheduler" pool-size="10"/> <task:executor id="myExecutor" pool-size="1"/>
생성 된 bean을 Spring bean 또는 Service Class에 삽입한다.
@Service public class DynamicJobExample { @Autowired @Qualifier("myScheduler") private TaskScheduler scheduler; public void schedule() throws ParseException { scheduler.schedule(new MyTask(), new CronTrigger("5 * * * * ?")); } }
MyTask는 Runnable 클래스 여야한다.
public class MyTask implements Runnable{ @Override public void run() { System.out.println("Hey, you reached me...:)"); } }
Maven 종속성은 (pom.xml)입니다.
<spring.version>4.1.0.RELEASE</spring.version> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency>
-
==============================
3.이런 식으로 JobDetail 및 Trigger 객체를 만들 수도 있습니다.
이런 식으로 JobDetail 및 Trigger 객체를 만들 수도 있습니다.
JobDetail jobDetail; String myJobClass = "com.MyJobClass"; String myJobName = "myJobName"; String myJobGroup ="myJobGroup"; Class myJobClassType= Class.forName(myJobClass); jobDetail =JobBuilder.newJob().ofType(myJobClassType) .withIdentity(myJobName, myJobGroup).build(); String myGroup = "myGroup"; String name = "TriggerName"; String expresion = "5 * * * * ?"; Trigger trigger = TriggerBuilder .newTrigger() .withIdentity(name, myGroup) .withSchedule( CronScheduleBuilder.cronSchedule(expresion)) .build();
-
==============================
4.
package com.myproject; import java.text.ParseException; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.triggers.CronTriggerImpl; import org.springframework.stereotype.Component; @Component public class QuartzSchedulerExample { public QuartzSchedulerExample() { SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory(); Scheduler scheduler; try { scheduler = schedFact.getScheduler(); JobDetail details = JobBuilder.newJob(MyMailBean.class) .withDescription("something") .withIdentity("mejob","myGroup") .storeDurably(true).build(); CronTriggerImpl trigger = new CronTriggerImpl(); trigger.setName("T1"); try { trigger.setCronExpression("0 0 0 * * ? *"); } catch (ParseException e) { e.printStackTrace(); } trigger.setDescription("desc"); scheduler.scheduleJob(details,trigger); scheduler.start(); } catch (SchedulerException e) { e.printStackTrace(); } } }
작업은 매일 00:00:00 (시 : 분 : 초)로 실행됩니다.
from https://stackoverflow.com/questions/17669445/java-example-dynamic-job-scheduling-with-quartz by cc-by-sa and MIT license
'SPRING' 카테고리의 다른 글
[SPRING] Spring 빈에서 새로운 트랜잭션 시작하기 (0) | 2019.03.01 |
---|---|
[SPRING] Spring에서 주석이있는 제 3 자 클래스를 어떻게 자동으로 작성합니까? (0) | 2019.03.01 |
[SPRING] 스프링 3 JSON (MVC 포함) (0) | 2019.03.01 |
[SPRING] Spring Controller의 Init 메소드 (주석 버전) (0) | 2019.03.01 |
[SPRING] 스프링 데이터 나머지로 n + 1 쿼리를 피하는 방법은 무엇입니까? (0) | 2019.03.01 |