메뉴 건너뛰기

목록
2022.09.17 19:46

quartz 기능 메모

profile
조회 수 19 댓글 1 예스잼 0 노잼 0

No Attached Image

구현할것 : DB 테이블에 cronexpression / 실행클래스 / 실행 method / 기타 데이터 저장 후 어플리케이션 구동시 스케쥴러 등록후 자동실행 처리

 

package com.example.quartz;

 

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.quartz.impl.StdSchedulerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.ApplicationArguments;

import org.springframework.boot.ApplicationRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.scheduling.quartz.CronTriggerFactoryBean;

import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;

 

import com.example.quartz.service.SchedulerService;

 

@SpringBootApplication

@EnableScheduling

public class QuartzApplication implements ApplicationRunner{

public static void main(String[] args) {

SpringApplication.run(QuartzApplication.class, args);

}

 

@Override

public void run(ApplicationArguments args) throws Exception {

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

// Create JOB

        MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();

        // Class.newInstance()

// 실행 패키지 내 클래스 지정

        jobDetail.setTargetObject(Class.forName("com.example.quartz.test.testClass").newInstance()); 

        

// Target Method

        jobDetail.setTargetMethod("test"); // TargetMethod : 실행할 프로세스가 정의된 method 명 지정

        jobDetail.setName("testSchedule"); // 스케쥴러의 이름 지정

        jobDetail.setConcurrent(false); //여러 작업을 동시에 실행해야 하는지 여부

        jobDetail.afterPropertiesSet();

        

        // Create CRON Trigger

// cronTrigger 설정

        CronTriggerFactoryBean cronTrigger = new CronTriggerFactoryBean();

        cronTrigger.setBeanName("CRON_" + "testSchedule");

 

        // Execute of CronExpression

        cronTrigger.setCronExpression("0 0/1 * 1/1 * ? *"); // cronexpression 지정

        cronTrigger.afterPropertiesSet();

 

        scheduler.scheduleJob((JobDetail) jobDetail.getObject(), cronTrigger.getObject());

scheduler.start();

}

 

}

 

 

나중에 써먹을수있게 메모해놔야지