spring boot引入quartz定时任务

版权声明:未经允许禁止转载、转发 https://blog.csdn.net/qq_22764659/article/details/87938713

spring boot引入quartz定时任务

首先是pom.xml配置

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-quartz</artifactId>
	</dependency>

1、定时任务时间配置@Scheduled(cron = “0 0/1 * * * ?”)

首先启动类中添加@EnableScheduling

@SpringBootApplication
@EnableScheduling
public class WebApplication {

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

其次是创建定时任务处理类

@Component
public class JobSchedule extends QuartzJobBean {
	/*// 每分钟启动
	@Scheduled(cron = "0 0/1 * * * ?")
	public void timerToNow() {
		System.out.println("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	}*/
}

2、 定时任务时间是可配置的

首先引入配置类

@Configuration
public class QuartzConfig {

	@Value("${asphale.schedule.time}")
	private int cronTime;

    @Bean
    public JobDetail teatQuartzDetail(){
        return JobBuilder.newJob(JobSchedule.class).withIdentity("jobQuartz").storeDurably().build();
    }
    @Bean
    public Trigger testQuartzTrigger(){
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(cronTime)  //设置时间周期单位秒
                .repeatForever();
        return TriggerBuilder.newTrigger().forJob(teatQuartzDetail())
                .withIdentity("testQuartz")
                .withSchedule(scheduleBuilder)
                .build();
    }
}

其次是定时任务执行类

@Component
public class JobSchedule extends QuartzJobBean {
	/**
     * 执行定时任务
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("quartz task "+new Date());
    }

}

猜你喜欢

转载自blog.csdn.net/qq_22764659/article/details/87938713