spring定時任務調度

本文將告訴你如何使用spring的任務調度。主要使用@Scheduled註解
<!-- more -->java

須要會使用maven

第一步 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>org.xxz</groupId>
    <artifactId>scheduled-task-test</artifactId>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第二步 定時任務類(ScheduledTasks)

package org.xxz.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ScheduledTasks {

    @Scheduled(fixedRate = 5000)
    public void now() {
        log.info("The time is now {}", new Date());
    }
}

@Scheduled有三種類型參數fixedRate, fixedDelay, cronspring

fixedRate 表示每隔多少毫秒執行一次apache

fixedDelay 表示任務執行完成後隔多少毫秒執行一次maven

cron 定時任務表達式spring-boot

第三步 啓動類(Application)

package org.xxz;

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

第四步 打包運行

cd scheduled-task-test
mvn clean package
java -jar target/scheduled-task-test-1.0.jar

擴展知識:若是不想使用spring的任務調度,可使用jdk自帶的任務調度類ui

ScheduledExecutorService#schedulecode

ScheduledExecutorService#scheduleAtFixedRatexml

ScheduledExecutorService#scheduleWithFixedDelayblog

今天的分享就到這裏了。謝謝閱讀。ip

原文地址:https://blog.uyiplus.com/2018/spring-scheduling-tasks/

相關文章
相關標籤/搜索