本片文章是對上一篇《SpringBoot整合Quartz》的升級。java
參考:http://www.javashuo.com/article/p-nqmlkfay-bq.htmlspring
<!--用到Me--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version> 4.3.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version> 4.3.9.RELEASE</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
@Configuration public class QuartzConfig { @Bean public SchedulerFactoryBean schedulerFactoryBean(){ SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); return schedulerFactoryBean; } @Bean public Scheduler scheduler(){ return schedulerFactoryBean().getScheduler(); } }
public class CloseTradeJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println("測試job = " + new Date()); } }
@Service public class MyTask { @Autowired public Scheduler scheduler; @PostConstruct //等同於init-method public void init(){ //定義jobdetail JobDetail jobDetail = JobBuilder.newJob(CloseTradeJob.class).withIdentity("close1", "closeTrade").build(); //定義trigger SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5) .repeatForever(); Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "closeTrade").startNow() .withSchedule(simpleScheduleBuilder).build(); //啓動job try { scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { e.printStackTrace(); } } }