springboot整合定时任务器(quartz)和task

导入坐标

 
            org.springframework.boot
            spring-boot-starter-quartz
        

添加任务需继承QuartzJobBean

public class myquartz extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
       /* System.out.println("quartz is running");*/
    }
}

添加配置类即触发器绑定任务

@Configuration
public class jobquarz {
 @Bean
    public JobDetail jobDetail(){//将任务添加进来
        JobDetail build = JobBuilder.newJob(myquartz.class).storeDurably().build();
        return build;
    }
    @Bean
    public Trigger trigger(){//设置触发器绑定jobdetail
        CronScheduleBuilder schbuild=CronScheduleBuilder.cronSchedule("0/5 * * *  * ?");
        Trigger build = TriggerBuilder.newTrigger().forJob(jobDetail()).withSchedule(schbuild).build();
        return build;
    }
}

2整合task比上面更加简单

在引导类中添加注解@EnableScheduling

@SpringBootApplication
@EnableCaching
@EnableScheduling
public class SpringbootCatchApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootCatchApplication.class, args);
    }

}

在任务方法上添加注解@Scheduled(cron = "0/2 * * * * ?")即可

   @Scheduled(cron = "0/2 * * * * ?")
    public void save(){
        System.out.println("running");
    }//需注入spring容器中

你可能感兴趣的:(spring,boot,java,mybatis)