quartz cron 값 변경
쿼츠를 이용하여 스케줄링 할 때 스케줄링 시간을 설정/변경 하고 싶을 때 아래와 같은 방법을 사용한다.
MainClass
public static void main(String[] args) { ... String cronStr = CommonUtil.getPropVal("MAIL.CRONTAB"); // properties 파일에서 읽기 SchedulerCronTrigger.getInstance(cronStr); ... } |
cronTriger class (singleton 으로 작성했다)
public class SchedulerCronTrigger { private static Logger logger = Logger.getLogger(SchedulerCronTrigger.class); private static volatile SchedulerCronTrigger INSTANCE; private SchedulerFactory schedFact = null; private Scheduler sched = null; private SchedulerCronTrigger() {} public static SchedulerCronTrigger getInstance(String cronStr) { if( INSTANCE == null ) { synchronized (SchedulerCronTrigger.class) { if( INSTANCE == null) { INSTANCE = new SchedulerCronTrigger(); INSTANCE.initInstance(cronStr); } } } return INSTANCE; } private void initInstance(String cronStr) { try { if(null == schedFact) { logger.debug("Create scheduler"); // 스케쥴 생성후 시작 schedFact = new StdSchedulerFactory(); sched = schedFact.getScheduler(); if(false == sched.isStarted()) { sched.start(); logger.debug("Start scheduler with ["+cronStr+"]"); JobDetail mailSender = new JobDetail("job", "mailSender", SendMail.class); CronTrigger trigger = null; try { trigger = new CronTrigger("trigger", "mailSender", cronStr); } catch(Exception e) { trigger = new CronTrigger("trigger", "mailSender", "0/10 * * * * ?"); // default 10초 마다 } sched.scheduleJob(mailSender, trigger); } } } catch (Exception e) { e.printStackTrace(); } } } |
실제 스케줄링 작업 (메일 전송)
public class SendMail implements Job{ private Logger logger = Logger.getLogger(SendMail.class); private MailService mailService;
public SendMail() { ApplicationContext context = new ClassPathXmlApplicationContext("framework/applicationContext.xml"); mailService = (MailService) context.getBean("mailService"); } @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { try { logger.debug("cheduler job execute"); mailService.sendMail(); } catch(Exception e) { logger.error("scheduler job execute exception"); logger.error(e.getMessage()); } } } |