欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot创建定时任务SchedulingTasks

程序员文章站 2022-07-26 20:42:28
新的学习方式:开始看一遍Spring官网的Guides1.在pom.xml中添加依赖 org.awaitility awaitility 3.1.2

新的学习方式:开始看一遍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.运行结果

SpringBoot创建定时任务SchedulingTasks

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