调度任务Scheduling Tasks

你需要什么

  • 大约15分钟
  • IntelliJ IDEA或其他编辑器
  • JDK 1.8或更高版本
  • Maven 3.2+

你会建立什么

您将构建一个应用程序,该应用程序使用Spring的 @Scheduled 注解,每5秒打印一次当前时间。

构建步骤

1、添加maven依赖

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

2、创建一个计划任务。

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

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

@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()));
    }
}

Scheduled注解定义了特定方法的运行时间。注意:此示例使用fixedRate,它指定从每次调用的开始时间开始测量的方法调用之间的时间间隔。还有 其他用法,你也可以直接看 API

3、启用计划

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

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

@EnableScheduling 确保创建后台任务执行程序。没有它,没有任何计划。

测试

启动项目,测试结果如下:

原文地址 https://spring.io/guides/gs/scheduling-tasks/

猜你喜欢

转载自blog.csdn.net/She_lock/article/details/80566888