seon99il

Spring

SpringBoot에서 Quartz Scheduler로 스케줄러 구현하기

5분 소요

java : 11 springBoot : 2.7.5

Part 1 : Learn about the Quartz Scheduler Part 2 : SpringBoot에서 Quartz Scheduler로 스케줄러 구현하기 Part 3 : Implement sending alerts at specific times per user with QuartzScheduler

이번 글에서는 Quartz Scheduler 설정과 간단한 예제를 구현해 봅니다.

이론적인 부분은 Part 1을 참고해 주세요.

프로젝트를 생성한 뒤 먼저 의존성과 .yml 파일을 설정합니다.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-quartz'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation'
}

JOB 정보는 DB(H2)에 저장하고 JPA를 사용하기로 했습니다.

server:
  port: 8080

spring:
  application:
    name: Quartz-Sample

  ## DataBase
  h2:
    console:
      enabled: true
      path: /h2
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:test;MODE=MySQL
    username: sa
    password:

  jpa:
    hibernate:
      ddl-auto: create-drop
    open-in-view: false
    show-sql: true
    properties:
      hibernate:
        format_sql: true
        use_sql_comments: true
        naming:
          physical-strategy = org.hibernate.model.naming.PhysicalNamingStrategyStandardImpl
    database: mysql
    generate-ddl: true

  quartz:
    job-store-type: jdbc
    jdbc:
      initialize-schema: always
    scheduler-name: "sample"

# Logging Info
logging:
  level:
    org.springframework: info

그리고 resources 폴더 아래에 quartz.properties를 생성합니다.

추가 설정 정보와 설명은 QuartzDoc을 참고해 주세요.

org.quartz.scheduler.instanceName=sample
org.quartz.scheduler.instanceId=AUTO
org.quartz.scheduler.rmi.export=false
org.quartz.scheduler.rmi.proxy=false
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=3
org.quartz.context.key.QuartzTopic=QuartzProperties
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.tablePrefix=QRTZ_
org.quartz.jobStore.isClustered=true

org.quartz.jobStore.dataSource=sample

org.quartz.dataSource.sample.provider=hikaricp
org.quartz.dataSource.sample.URL = jdbc:h2:mem:test;MODE=MySQL
org.quartz.dataSource.sample.driver = org.h2.Driver
serverTimezone=UTC&characterEncoding=UTF-8
org.quartz.dataSource.sample.user = sa

경험해 보셨는지 모르겠지만, Job 클래스에서는 기본적으로 DI(의존성 주입)를 사용할 수 없습니다. 하지만 많은 기능이 DI를 통해 실행되므로, Job.class를 돕기 위해 AutoWiringSpringBeanJobFactory.class를 만들겠습니다.

public class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        beanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);

        return job;
    }
}

그다음 Part 1에서 설명한 Listener를 구현합니다. JobListener는 Job 실행 전후의 이벤트를, TriggerListener는 Trigger 실행 전후의 이벤트를 받을 수 있습니다.

@Slf4j
public class JobsListener implements JobListener {

    @Override
    public String getName() {
        return "JobsListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        log.info("Before Start Job");
        JobKey jobKey = context.getJobDetail().getKey();

        log.info("jobKey : {}", jobKey);

    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        log.info("Operation aborted");
        JobKey jobKey = context.getJobDetail().getKey();

        log.info("jobKey : {}", jobKey);

    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        log.info("Job Was Executed");
        JobKey jobKey = context.getJobDetail().getKey();

        log.info("jobKey : {}", jobKey);

    }
}
@Slf4j
public class TriggersListener implements TriggerListener {

    @Override
    public String getName() {
        return "TriggersListener";
    }

    @Override
    public void triggerFired(Trigger trigger, JobExecutionContext context) {
        log.info("Trigger is Starting");
        final JobKey jobKey = trigger.getJobKey();

        log.info("triggerFired at {} :: jobKey : {}", trigger.getStartTime(), jobKey);

    }

    /**
     * @Content : if this return value is true, 
     * request to JobListener jobExecutionVetoed()
     */
    @Override
    public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) {
        log.info("check Trigger health");

        return false;
    }

    @Override
    public void triggerMisfired(Trigger trigger) {
        log.info("Trigger Misfired");
        final JobKey jobKey = trigger.getJobKey();

        log.info("triggerMisfired at {} :: jobKey : {}", trigger.getStartTime(), jobKey);

    }

    @Override
    public void triggerComplete(Trigger trigger, JobExecutionContext context,
                                Trigger.CompletedExecutionInstruction triggerInstructionCode) {
        log.info("Trigger Complete");
        final JobKey jobKey = trigger.getJobKey();

        log.info("triggerMisfired at {} :: jobKey : {}", trigger.getStartTime(), jobKey);

    }
}

이제 앞서 작성한 설정 정보를 사용합니다.

@Slf4j
@Configuration
@RequiredArgsConstructor
public class QuartzConfig {
    private final DataSource dataSource;
    private final ApplicationContext applicationContext;
    private final PlatformTransactionManager platformTransactionManager;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        AutoWiringSpringBeanJobFactory autoWiringSpringBeanJobFactory = new AutoWiringSpringBeanJobFactory();

        autoWiringSpringBeanJobFactory.setApplicationContext(applicationContext);
        schedulerFactoryBean.setJobFactory(autoWiringSpringBeanJobFactory);
        schedulerFactoryBean.setDataSource(dataSource);
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        schedulerFactoryBean.setAutoStartup(true);
        schedulerFactoryBean.setTransactionManager(platformTransactionManager);
        schedulerFactoryBean.setQuartzProperties(quartzProperties());
        return schedulerFactoryBean;
    }

    private Properties quartzProperties() {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("quartz.properties"));
        Properties properties = null;

        try {
            propertiesFactoryBean.afterPropertiesSet();
            properties = propertiesFactoryBean.getObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

}

이제 Trigger를 통해 실행될 동작을 구현합니다. Job 클래스에서는 @RequiredArgsConstructor가 동작하지 않으므로 반드시 @Autowired를 사용해야 합니다.

/**
 *  an interface to be implemented by components that you wish to have executed by the scheduler
 */
@Slf4j
@Component
@PersistJobDataAfterExecution // to change the job data map when a job runs
@DisallowConcurrentExecution
public class SampleJob implements Job {

    @Autowired
    private TestRepository testRepository;

    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        System.out.println(this.getClass().getName() + "Sample Job Start! [ " + LocalDate.now() + " ]");

    }
}

이 Job이 Trigger에 의해 호출되면 execute 메서드의 내용이 실행됩니다.

Job 생성과 Trigger 생성은 QuartzHandler에서 관리하겠습니다.

/**
 * Managing Trigger and Job Creation
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class QuartzHandler {
    private final Scheduler scheduler;

    @PostConstruct
    public void init() {
        try {
            // Initialization (DB, Scheduler)
            scheduler.clear();

            // set JobListener
            scheduler.getListenerManager()
                    .addJobListener(new JobsListener());

            // set TriggerListener
            scheduler.getListenerManager()
                    .addTriggerListener(new TriggersListener());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // add Job
    public <T extends Job> void addJob(
            Class<? extends Job> job, final String name, String description, Map paramsMap, String cron)
            throws SchedulerException {

        JobDetail jobDetail = buildJobDetail(job, name, description, paramsMap);
        Trigger trigger = buildCronTrigger(cron);

        if (scheduler.checkExists(jobDetail.getKey())) { // if already job -> change
            scheduler.deleteJob(jobDetail.getKey());
            scheduler.scheduleJob(jobDetail, trigger);

        } else {
            scheduler.scheduleJob(jobDetail, trigger);
        }
    }

    // create JobDetail
    public <T extends Job> JobDetail buildJobDetail(
            Class<? extends Job> job,final String jobName, final String jobDescription, Map paramsMap) {

        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.putAll(paramsMap);

        return JobBuilder.newJob(job)
                .withIdentity(jobName)
                .withDescription(jobDescription)
                .usingJobData(jobDataMap)
                .build();
    }

    // create CronTrigger
    private Trigger buildCronTrigger(String cronExp) {
        CronTriggerFactoryBean cronTriggerFactory = new CronTriggerFactoryBean();
        cronTriggerFactory.setCronExpression(cronExp);
        cronTriggerFactory.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
        try {
            cronTriggerFactory.afterPropertiesSet();
        } catch (ParseException e) {
            e.printStackTrace();

        }
        return cronTriggerFactory.getObject();

    }
}

이제 요청을 통해 Job을 생성합니다. 예) localhost:8080/jobs/10

@Slf4j
@RestController
@RequiredArgsConstructor
public class QuartzController {
    private final QuartzHandler quartzHandler;

    @RequestMapping("/jobs/{second}")
    public void createJobSample(@PathVariable final String second) throws SchedulerException {
        log.info("[ {} ]--------------------- creatJob Start ! ", LocalTime.now());
        final String cron = second + " * * * * ?";

        Map<String, Object> map = new HashMap<>();
        map.put("name", this.getClass().getName());

        quartzHandler.addJob(SampleJob.class, "jobName", "SampleDescription", map, cron);

    }
}

로그 결과

Listener와 Job이 모두 정상적으로 동작하는 것을 확인할 수 있으며, 설정한 DB에서도 이 Trigger 정보를 찾을 수 있습니다.

H2 Database

다음 글에서는 최종 목표인, DB에 저장된 시간의 5분 전에 Job을 실행하는 서비스를 구현하겠습니다.

코드는 제 GitHub에서 확인하실 수 있습니다.

GitHub - Seonggil-Jeong/QuartzScheduler-Sample

이전 글

전체 글 보기 →

댓글