SpringBoot整合Quartz(升級版)

本片文章是對上一篇《SpringBoot整合Quartz》的升級。java

建立SpringBoot項目

參考:http://www.javashuo.com/article/p-nqmlkfay-bq.htmlspring

添加Quartz依賴,配置pom文件

<!--用到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>

建立QuartzConfig配置類

@Configuration
public class QuartzConfig {

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        return schedulerFactoryBean;
    }

    @Bean
    public Scheduler scheduler(){
        return schedulerFactoryBean().getScheduler();
    }
}

建立job

public class CloseTradeJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("測試job = " + new Date());
    }
}

建立Task

@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();
        }
    }
}

測試

相關文章
相關標籤/搜索