1.导包
// Quartz
compile('org.springframework.boot:spring-boot-starter-quartz')
2.写需要定时执行的任务类(job)
继承QuartzJobBean类
重写executeInternal方法(这里是定时执行的代码)
public class WeatherDataSyncJob extends QuartzJobBean {
private final static Logger logger = LoggerFactory.getLogger(WeatherDataSyncJob.class);
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
logger.info("Weather Data Sync Job. Start!");
}
}
3.写Quartz的配置类(注意红色字体写入自己的任务类)
@Configuration
public class QuartzConfiguration {
private static final int TIME = 2; // 更新频率
// JobDetail
@Bean
public JobDetail weatherDataSyncJobDetail() {
return JobBuilder.newJob(WeatherDataSyncJob.class).storeDurably()
.build();
}
// Trigger
@Bean
public Trigger weatherDataSyncTrigger() {
SimpleScheduleBuilder schedBuilder = SimpleScheduleBuilder
.simpleSchedule().withIntervalInSeconds(TIME).repeatForever();
return TriggerBuilder.newTrigger().forJob(weatherDataSyncJobDetail())
.withSchedule(schedBuilder).build();
}
}
4.运行结果(每2秒执行一次任务)
5.非Boot环境中的使用
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
任务调度
参数传递
定时任务中获取参数
方法参数arg0(下面图片中的context)可以获取JobDetail和Trigger的信息(包括想向任务传递的参数)
Cron表达式