SpringBoot创建定时任务SchedulingTasks

2022-08-02,,

新的学习方式:开始看一遍Spring官网的Guides

1.在pom.xml中添加依赖

        <dependency>
            <groupId>org.awaitility</groupId>
            <artifactId>awaitility</artifactId>
            <version>3.1.2</version>
            <scope>test</scope>
        </dependency>

2.创建进行定时任务的类ScheduledTasks.java

在定时运行的方法上加注解@Scheduled,这里是每5000ms运行一次reportCurrentTime()。
fixedRate指时间间隔从每次调用的开始时间算起,还可以选择fixedDelay从每次完成算起。

package com.example.schedulingtasks;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
public class ScheduledTasks {
    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

3.在主程序类上加注解@EnableScheduling

package com.example.schedulingtasks;

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

@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {

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

}

4.运行结果

本文地址:https://blog.csdn.net/weixin_42970433/article/details/107381218

《SpringBoot创建定时任务SchedulingTasks.doc》

下载本文的Word格式文档,以方便收藏与打印。