quartz简单demo,教你最快使用quartz
发布日期:2025-05-05 23:03:26 浏览次数:4 分类:精选文章

本文共 2755 字,大约阅读时间需要 9 分钟。

Quartz入门实例:Spring集成定时任务

作为一名开发人员,今天我决定研究一下如何在Spring Boot项目中集成Quartz定时任务。目标是每20秒输出一句内容。虽然我对Quartz有一些基本了解,但具体的配置流程还是需要一步步来。

项目创建

首先,我创建了一个Spring Boot项目,使用Spring Initializer,选择了Spring Boot Starter Web和Quartz Starter。这样可以简化依赖管理,减少手动配置的麻烦。

配置文件

接下来,我创建了application.properties文件。在这个文件中,我添加了以下内容:

spring.quartz.job-store-type=PERSISTENT
spring.quartz.scheduler.startDelay=10
spring.quartz.cronExpression=0/20 * * * *

这里,PERSISTENT用于持久化存储任务,防止重启时丢失。startDelay设置为10秒,避免在应用启动时立即触发任务。cronExpression设置为“0/20 * * * *”,每隔20秒触发一次任务。

任务处理类

然后,我创建了一个处理任务的类TaskDemo

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.slf4j.Logger.getLogger;
@Component
public class TaskDemo {
private static final Logger LOGGER = getLogger(TaskDemo.class);
@Autowired
private JobDetail jobDetail;
@Autowired
private Scheduler scheduler;
public void doTask() {
LOGGER.info("dddd");
System.out.println("日志输出");
System.out.println("定时任务测试");
}
@Autowired
public void setJobDetail(JobDetail jobDetail) {
this.jobDetail = jobDetail;
}
public void run() throws Exception {
scheduler.triggerJob(jobDetail);
}
}

这个类包含了一个doTask方法,用于执行定时任务。它使用了Logger来记录日志信息,并通过System.out.println打印输出。

配置任务

接下来,我需要将这个任务配置到Quartz中。为此,我创建了applicationContext-scheduler.xml文件:

测试配置

application.properties中添加以下内容:

spring.main.web.env=true

这样,Spring Boot会将上下文配置加载到Web环境中。

测试运行

创建一个测试类TaskDemoApplication

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TaskDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TaskDemoApplication.class, args);
}
}

查看日志

运行应用程序后,检查控制台输出,应该每隔20秒看到一次“dddd”。

验证配置

为了确认配置是否正确,我可以使用Quartz的监控工具,或者查看任务调度器的日志。可以使用以下命令查看Quartz的状态:

curl http://localhost:8080/monitor

注意事项

  • 依赖管理:确保所有依赖已经添加,包括Spring Boot Starter和Quartz Starter。

  • 配置文件路径:确保applicationContext-scheduler.xml位于正确的路径下,通常是在src/main/resources/static/app-context.xmlsrc/main/resources/applicationContext-scheduler.xml

  • 任务调度器:确保SchedulerFactoryBeanCronTriggerFactoryBean正确注册,并且taskDemoJobDetailtaskDemo都存在。

  • 任务扫描:确保@ComponentScan正确配置,扫描到TaskDemo类。

  • 调试日志:可以在TaskDemo类中添加更多日志输出,帮助调试和确认任务是否正常运行。

  • 通过以上步骤,我成功地将一个简单的Quartz定时任务集成到Spring Boot项目中,每隔20秒输出一句内容。虽然过程中遇到了一些问题,但通过仔细阅读文档和调试,最终顺利解决了。

    上一篇:PlutoSDR学习笔记(一)—函数API手册
    下一篇:PLSQL的DBMS_GETLINE

    发表评论

    最新留言

    留言是一种美德,欢迎回访!
    [***.207.175.100]2026年06月16日 09时26分35秒

    关于作者

        喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
    -- 愿君每日到此一游!

    推荐文章