1. 程式人生 > >spring boot 任務排程

spring boot 任務排程

1.依賴檔案

檔名:pom.xml

檔案內容:

<?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>com.huinongtx.springboot</groupId>

    <artifactId>demoschedulingtasks</artifactId>

    <version>1.0-SNAPSHOT</version>


    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.0.5.RELEASE</version>

    </parent>


    <dependencies>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter</artifactId>

        </dependency>

    </dependencies>


    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

</project>

2.業務類

包名:com.huinong.springboot.hello

類名:ScheduledTasks

類內容:

package com.huinong.springboot.hello;

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;

/**

* Created by dengdashuai on 2018/12/6.

*/

@Component

public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);


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


    // 5秒執行一次該方法

    @Scheduled(fixedRate = 5000)

    public void reportCurrentTime(){

        log.info("The time is now {}", dateFormat.format(new Date()));

    }

}

3.應用入口檔案

包名:com.huinong.springboot.hello

類名:Application

類內容:

package com.huinong.springboot.hello;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.scheduling.annotation.EnableScheduling;

/**

* Created by dengdashuai on 2018/12/6.

*/

@SpringBootApplication

// 開啟任務排程

@EnableScheduling

public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class);

    }

}

4.專案目錄結構截圖

4.png

5.執行結果截圖

1.png

QQ截圖20181206153448.png