SpringBoot整合Quartz定时任务 的简单实例

时间:2022-05-03
本文章向大家介绍SpringBoot整合Quartz定时任务 的简单实例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

POM.XML文件

<!-- 定时器任务 quartz需要导入的坐标 -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>1.8.5</version>
        </dependency>

类似于控制器代码:

package com.xiaowu.quartz.demo;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/***
 * 
 * Quartz设置项目全局的定时任务
 * 
 * @Component注解的意义        泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。一般公共的方法我会用上这个注解
 * 
 * 
 * @author WQ
 *
 */
@Component
public class QuartzDemo {
    
    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void work() throws Exception {
        System.out.println("执行调度任务:"+new Date());
    }
    
    
    @Scheduled(fixedRate = 5000)//每5秒执行一次
    public void play() throws Exception {
        System.out.println("执行Quartz定时器任务:"+new Date());
    }

    
    
    @Scheduled(cron = "0/2 * * * * ?") //每2秒执行一次
    public void doSomething() throws Exception {
        System.out.println("每2秒执行一个的定时任务:"+new Date());
    }

    
    
    
    @Scheduled(cron = "0 0 0/1 * * ? ") // 每一小时执行一次
    public void goWork() throws Exception {
        System.out.println("每一小时执行一次的定时任务:"+new Date());
    }
    
    
    
    
}

启动SpringBoot项目,即可。

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

截图如下: