본문 바로가기

spring

Quartz Tutorials 정리(중)

 

1. Quartz Main Component and Example 

 

  • Scheduler - the main API for interacting with the scheduler
  • Job - 스케줄러에 의해 실행되는 컴포넌트들을 구현한 인터페이스 
  • JobDetail - Job 의 인스턴스를 생성
  • Trigger - 잡의 실행(스케줄링)에 관해 정의
  • JobBuilder - job 인스턴스를 생성하는 JobDetail 의 인스턴스를 생성 정의
  • TriggerBuilder - 트리거를 생성 정의  

 

- Scheduler는 SchedulerFactory 에 의해서 생성된다. 

- 생성된 Scheduler에 의해서 Job 과 트리거가 추가 되고 삭제 될 수 있다.

 

  SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();

        scheduler.start();

        // define the job and tie it to our HelloJob class
        JobDetail job = JobBuilder.newJob(HelloJob.class)
                .withIdentity("myJob", "group1")
                .build();

        // Trigger the job to run now, and then every 40 second
        Trigger trigger =  TriggerBuilder.newTrigger()
                .withIdentity("myTrigger", "group1")
                .startNow()
                .withSchedule(simpleSchedule()
                    .withIntervalInSeconds(40)
                    .repeatForever())
                .build();

        // Tell quartz to schedule the job using our trigger
        scheduler.scheduleJob(job, trigger);

 

SchedulBuilder를 상속하고 있는 클래스들이다. 

이 클래스들을 이용하여 다양한 타입의 schedule 을 정의할 수 있다. 

import static org.quartz.JobBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;
import static org.quartz.CronScheduleBuilder.*;
import static org.quartz.CalendarIntervalScheduleBuilder.*;
import static org.quartz.TriggerBuilder.*;
import static org.quartz.DateBuilder.*;

 DateBuilder 는 Date 인스턴스를 쉽게 생성할 수 있는 메서드들을 제공한다.

 

2. Jobs and Triggers

 

2.1 The Job Interface

 Job 은 Job 인터페이스를 구현한 클래스이며, 단 하나의 메서드만 가지고 있다. 

  package org.quartz;

  public interface Job {

    public void execute(JobExecutionContext context)
      throws JobExecutionException;
  }

 

- Job 에 등록된 트리거가 실행될때 스케줄러의 Worker thread중의 하나가 execute 메서드를 호출한다.

- 메서드에 전달된 JobExecutionContext 오브젝트는 "run-time" 환경에 관한 정보를 가진 Job instance 를 제공한다. 

 

http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-02.html

 

Tutorial 2

Lesson 2: The Quartz API, Jobs And Triggers The key interfaces of the Quartz API are: Scheduler - the main API for interacting with the scheduler. Job - an interface to be implemented by components that you wish to have executed by the scheduler. JobDetail

www.quartz-scheduler.org

 

3. More About Triggers

3.1 Common Trigger Attributes

 TriggerBuilder 를 이용해서 Trigger 속성을 정의 할 수 있다. 

  • "jobKey" : 트리거가 실행 될때 실행되어야 하는 잡을 식별 하는 키
  • "startTime" :  java.util.Date 타입
  • "endTime"  

3.2 Priority

 트리거의 우선순위를 정할 수 있다. 쿼츠는 모든 트리거를 한번에 실행할 수 있는 충분한 리소스를 

가지고 있지 않기 떄문이다.

 

3.3 Calendars 

 쿼츠의 캘린더 오브젝트는 트리거가 생성되고 스케줄러에 저장될때 같이 사용될 수 있는데. 

Calenars 는 Calendars are useful for excluding blocks of time from the the trigger’s firing schedule. 할떄 유용하다.

예를들어, 9시 30분에 잡을 실행하도록 트리거를 추가하지만 공휴일은 제외하는 기능을 추가 할 수 있다.

package org.quartz;

public interface Calendar {

  public boolean isTimeIncluded(long timeStamp);

  public long getNextIncludedTime(long timeStamp);

}

- timeStamp 의 파라미터 타입이 Long 인점을 감안할때 millisecond 의 포맷임을 확인 할 수 있다.

- 공휴일 추가 안할거니까 담에 보기,

http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-04.html

 

Tutorial 4

Lesson 4: More About Triggers Like jobs, triggers are quite easy to work with, but do contain a variety of customizable options that you need to be aware of and understand before you can make full use of Quartz. Also, as noted earlier, there are different

www.quartz-scheduler.org

   

4. Simple Triggers        

Simple 트리거는 오직 한번 실행되며 한번 시점에서 반복기능도 가능하다. 

start-end, end-time, repeat count, repeat inteval 의 속성을 가지고 있다. 

 

- 한번 실행되는 트리거, 반복 없음

SimpleTrigger trigger = (SimpleTrigger)  TriggerBuilder.newTrigger()
    .withIdentity("trigger1", "group1")
    .startAt(myStartTime) // some Date
    .forJob("job1", "group1") // identify job with name, group strings
    .build();

- 한번 실행되는 트리거, 10초마다 10번 실행 

 trigger =  TriggerBuilder.newTrigger()
    .withIdentity("trigger3", "group1")
    .startAt(myTimeToStartFiring)  // if a start time is not given (if this line were omitted), "now" is implied
    .withSchedule(simpleSchedule()
        .withIntervalInSeconds(10)
        .withRepeatCount(10)) // note that 10 repeats will give a total of 11 firings
    .forJob(myJob) // identify job with handle to its JobDetail itself                   
    .build();

http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-05.html

 

Tutorial 5

Lesson 5: SimpleTrigger SimpleTrigger should meet your scheduling needs if you need to have a job execute exactly once at a specific moment in time, or at a specific moment in time followed by repeats at a specific interval. For example, if you want the tr

www.quartz-scheduler.org

 

5. Cron Triggers    

- SimpleTrigger 보다 더 많이 쓰인다. 

- 반복하여 실행할때 사용한다.

- 예를 들어 금요일 저녁 마다, 매일 9시 30분에, 월요일 9 - 10시 사이의 5분 마다,

  2월의 월요일, 수요일, 금요일마다

- startTime, endTime 을 가지고 있다. 

 

5.2 Cron Expressions

- 7개의 표현식(sub-expressions) 으로 구성되어 있는데, 공백으로 구분된다.

  • Seconds
  • Minutes
  • Hours
  • Day-of-Month
  • Month
  • Day-of-Week
  • Year (optional field)

 예를 들어,

- " 0 0 12 ? * WED " 는 수요일 12시를 의미한다. 

Individual sub-expressions can contain ranges and/or lists. For example, the day of week field in the previous (which reads “WED”) example could be replaced with “MON-FRI”, “MON,WED,FRI”, or even “MON-WED,SAT”.

- * 는 "every" 를 의미하는데, Month 에 * 가 있으면 매달, 모든 달을 의미한다.

- Day-Of-Week 필드에 * 가 있으면 evry day of the week 를 의미한다. 

- 기타 예제는 

http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-06.html 

 

Tutorial 6

Lesson 6: CronTrigger CronTrigger is often more useful than SimpleTrigger, if you need a job-firing schedule that recurs based on calendar-like notions, rather than on the exactly specified intervals of SimpleTrigger. With CronTrigger, you can specify firi

www.quartz-scheduler.org

 

6. TriggerListeners and JobListeners

- 각각 Trigger 와 Job 에 관한 이벤트

- 관련 이벤트는 trigger firings, trigger mis-firings, trigger completions 

- The org.quartz.TriggerListener Interface

public interface TriggerListener {

    public String getName();

    public void triggerFired(Trigger trigger, JobExecutionContext context);

    public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context);

    public void triggerMisfired(Trigger trigger);

    public void triggerComplete(Trigger trigger, JobExecutionContext context,
            int triggerInstructionCode);
}

- The org.quartz.JobListener Interface

public interface JobListener {

    public String getName();

    public void jobToBeExecuted(JobExecutionContext context);

    public void jobExecutionVetoed(JobExecutionContext context);

    public void jobWasExecuted(JobExecutionContext context,
            JobExecutionException jobException);

}

 

- The org.quartz.SchedulerListener Interface    

 

public interface SchedulerListener {

    public void jobScheduled(Trigger trigger);

    public void jobUnscheduled(String triggerName, String triggerGroup);

    public void triggerFinalized(Trigger trigger);

    public void triggersPaused(String triggerName, String triggerGroup);

    public void triggersResumed(String triggerName, String triggerGroup);

    public void jobsPaused(String jobName, String jobGroup);

    public void jobsResumed(String jobName, String jobGroup);

    public void schedulerError(String msg, SchedulerException cause);

    public void schedulerStarted();

    public void schedulerInStandbyMode();

    public void schedulerShutdown();

    public void schedulingDataCleared();
}

 

 

- 스케줄러 추가/제거

scheduler.getListenerManager().addSchedulerListener(mySchedListener);
scheduler.getListenerManager().removeSchedulerListener(mySchedListener);

 

7. Job Store

 - JobStore 는 스케줄러에 제공한 작업데이터를 추적하는 역할을 한다. 

- 작업데이터란? job, triggers, calendars 등이 있다. 

- 쿼츠 스케줄러에게 적당한 JobStore는 선택하는것은 매우 중요하다.

- 잡 스토어 종류

 1) RAMJobStore

 2) JDBCJobStore

 3) TerracottaJobStore

http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-09.html

 

Tutorial 9

Lesson 9: Job Stores JobStore’s are responsible for keeping track of all the “work data” that you give to the scheduler: jobs, triggers, calendars, etc. Selecting the appropriate JobStore for your Quartz scheduler instance is an important step. Lucki

www.quartz-scheduler.org

8. Configuration, Resource Usge and SchedulerFactory

 - Quartz 아키텍처는 모듈식 이므로 실행 하려면 여러 구성요소를 함께 연결 해야한다. 

 - Quartz가 작업을 수행하기 전에 구성해하는 주요 컴포넌트는 다음과 같다.

  • ThreadPool
  • JobStore
  • DataSources ( if necessary) 
  • The Scheduler itself

8.1 ThreadPool

 ThreadPool은 작업을 실행할 때 사용할 Quartz용 스레드 집합을 제공합니다. 풀에 스레드가 많을 수록

더 많은수의 잡이 동시적으로 실행될 수 있다. 그러나 스레드가 너무 많으면 시스템이 다운 될 수 있으며,

대부분의 Quartz 사용자는 5개 정도의 스레드가 충분하다는 것을 알 수 있다. 

 

8.2 JobStore

8.3 DataSources - 7번에서 다룸

8.4 The Scheduler itself

  1) StdSchedulerFactory

  2) DirectSchedulerFactory

8.5 Logging

 - Quartz 는 SLF4J 프레임 워크를 사용

반응형