当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot创建定时任务SchedulingTasks

SpringBoot创建定时任务SchedulingTasks

2020年07月17日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网