2021-05-12

springboot通过注解实现定时任务

1.创建工程

2.在pom.xml中添加项目依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>schedule</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-parent</artifactId>
        <version>2.2.0.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

3.编写启动类.

在启动类中添加 @EnableScheduling注解

package com.demo.schedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @className: ScheduleApplication
 * @description: 启动类
 * @author: penghailan
 * @create: 2021-04-02 16:41
 **/
@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class,args);
    }
}

4.编写定时方法

在目标方法中添加 @Scheduled注解,

同时在 @Scheduled注解中添加触发定时任务的元数据。

package com.demo.schedule.testSchedule;

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

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @className: TestSchedule
 * @description: 测试定时器
 * @author: penghailan
 * @create: 2021-04-02 16:43
 **/

@Component
public class TestSchedule {
    @Scheduled(cron = "0/30 * * * * ?")//零秒开始,没三十秒打印一次
    public static void printTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = sdf.format(new Date());
        System.out.println(format);
    }
}

最后,启动项目,看到没三十秒打印出当前时间
2021-05-12

5.工程结构

2021-05-12

上一篇:SpringBoot定时任务Task常用开发方式


下一篇:springboot之定时任务(三种方式)