Spring Boot 原生 @Scheduled
任务配置
@Slf4j
@Component
public class ScheduledTask {
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() throws InterruptedException {
log.info(new Date());
}
@Scheduled(fixedDelay = 5000)
public void reportCurrentTimeAfterSleep() throws InterruptedException {
log.info(new Date());
}
@Scheduled(cron = "0 0 1 * * *")
public void reportCurrentTimeCron() throws InterruptedException {
log.info(new Date());
}
}
启动
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Spring Boot 结合 Quartz 实现动态设置定时任务
添加依赖配置
implementation 'org.springframework.boot:spring-boot-starter-quartz'
配置 quartzJobFactory 和 scheduler 对象
package com.xiaozhangge.quartz.configure;
import org.quartz.Scheduler;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Component;
@Configuration
public class QuartzConfiguration {
@Component("quartzJobFactory")
class QuartzJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
final Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
@Bean(name = "scheduler")
public Scheduler scheduler(SchedulerFactoryBean schedulerFactoryBean) throws Exception {
Scheduler scheduler = schedulerFactoryBean.getScheduler();
scheduler.start();
return scheduler;
}
}
新建一个bean对象,用来保存基本的job信息
package com.xiaozhangge.quartz.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class QuartzJob {
public static final Integer STATUS_RUNNING = 1;
public static final Integer STATUS_NOT_RUNNING = 0;
public static final Integer CONCURRENT_IS = 1;
public static final Integer CONCURRENT_NOT = 0;
private String jobId;
private String cronExpression;
private String methodName;
private Integer isConcurrent;
private String description;
private String beanName;
private String triggerName;
private Integer jobStatus;
private String jobName;
}
新建一个统一的QuartzManager,用来统一管理job
package com.xiaozhangge.quartz.configure;
import com.xiaozhangge.quartz.bean.QuartzJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
@Slf4j
@Component
public class QuartzManager {
@Resource(name = "scheduler")
private Scheduler scheduler;
public void addJob(QuartzJob job) throws SchedulerException, ClassNotFoundException, IllegalAccessException, InstantiationException {
Class<?> clazz = Class.forName(job.getBeanName());
Job jobEntity = (Job) clazz.newInstance();
JobDetail jobDetail = newJob(jobEntity.getClass())
.withIdentity(job.getJobName()).build();
Trigger cronTrigger = newTrigger()
.withIdentity(job.getTriggerName())
.startNow()
.withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression()))
.build();
scheduler.scheduleJob(jobDetail, cronTrigger);
}
public void updateJobCron(QuartzJob quartzJob) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(quartzJob.getJobName());
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression());
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
scheduler.rescheduleJob(triggerKey, trigger);
}
public void deleteJob(QuartzJob quartzJob) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(quartzJob.getJobName());
scheduler.deleteJob(jobKey);
}
public void resumeJob(QuartzJob quartzJob) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(quartzJob.getJobName());
scheduler.resumeJob(jobKey);
}
public void runAJobNow(QuartzJob quartzJob) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(quartzJob.getJobName());
scheduler.triggerJob(jobKey);
}
public void pauseJob(QuartzJob quartzJob) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(quartzJob.getJobName());
scheduler.pauseJob(jobKey);
}
}
新建job任务,实现org.quartz.Job接口
package com.xiaozhangge.quartz.schedule;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
@Slf4j
@Component
public class ScheduleTask extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) {
log.info("execute task:{}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.CHINA)));
}
}
启动类配置
package com.xiaozhangge.quartz;
import com.xiaozhangge.quartz.bean.QuartzJob;
import com.xiaozhangge.quartz.configure.QuartzManager;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QuartzSchedulerApplication implements CommandLineRunner {
@Autowired
private QuartzManager quartzManager;
public static void main(String... args) {
SpringApplication.run(QuartzSchedulerApplication.class, args);
}
@Override
public void run(String... args) {
try {
String scheduleTask = "com.xiaozhangge.quartz.schedule.ScheduleTask";
QuartzJob job = new QuartzJob(scheduleTask,
"*/1 * * * * ?",
scheduleTask,
1,
scheduleTask,
scheduleTask,
scheduleTask,
QuartzJob.STATUS_NOT_RUNNING,
scheduleTask);
quartzManager.addJob(job);
} catch (SchedulerException | ClassNotFoundException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
}