SpringBoot集成Quartz入门
文章目录
前言
Quartz 是一个完全由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。—by W3Cschool
开始入门
首先我们要从Maven中引入spring-boot-starter-quartz
<!--SpringBoot集成QuartZ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>springboot配置,可选,配置项可去官方文档查看
#Quartz
spring.quartz.job-store-type=memory
spring.quartz.auto-startup=true
spring.quartz.overwrite-existing-jobs=true
spring.quartz.wait-for-jobs-to-complete-on-shutdown=true然后新建个quartz配置类
@Configuration
public class QuartzConfig {
@Bean
public JobDetail jobDetail_1() {
return JobBuilder.newJob(TestJob.class) //被执行的类
.withIdentity("jobDetail_1")
.storeDurably().build();
}
@Bean
public Trigger myTrigger() {
return TriggerBuilder.newTrigger()
.forJob("jobDetail_1")
.withIdentity("myTrigger")
.startNow()
.withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * 1 * ? *")) //任务调度cron表达式,这里以字符串传递,后台可动态配置
.build();
}
}最后写个被执行的方法即可, 改类继承QuartzJobBean并且要实现executeInternal方法,在executeInternal方法里编写调度逻辑
@Service
@Async
public class TestJob extends QuartzJobBean {
private final Logger logger = LoggerFactory.getLogger(TestJob.class);
private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@Override
protected void executeInternal(JobExecutionContext context) {
logger.info("定时器执行:" + sdf.format(new Date()));
}
}踩坑说明
如果上面方法都编写完毕并且运行起来,但是任务没有被执行,控制台也没有报错的这种情况下多半是配置文件没有生效,我这边的情况是配置类并没有被springboot扫描到,所以我的解决方案如下:
@EnableAsync
@EnableScheduling
@SpringBootApplication(scanBasePackages = "com.jwss")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}主要是加上了这个,让它扫描到我项目所有的代码
scanBasePackages = "com.jwss"

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论