Spring Boot如何进行任务调度呢?

戚薇 SpringBoot 发布时间:2023-06-07 22:04:26 阅读数:10583 1
下文笔者讲述SpringBoot实现任务调度的方法分享,如下所示
使用@Scheduled注解
    即可实现任务调度
例:实现任务调度
 
Maven依赖

<?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>org.example</groupId>
    <artifactId>SchedulingTasks</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.10.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.awaitility</groupId>
            <artifactId>awaitility</artifactId>
            <version>3.1.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
//创建调度调度任务的类
//ScheduleTasks.java
package com.java265.component;
 
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(fixedDelay = 5000)
    public void reportCurrentTime(){
 
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

@Scheduled注解
   fixedDelay指定每多少毫秒调用一次

此处还可以使用corn
   如:
     @Scheduled(cron="...")
package com.java265;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
 
@SpringBootApplication
@EnableScheduling
public class Main {
 
    public static void main(String[] args){
 
        SpringApplication.run(Main.class, args);
    }
} 
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202306/6741.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者