SpringBoot教程(二)构建定时任务

一、本地环境

  • 操作系统:Mac OS X 10.13.2
  • 编辑器:IntelliJ IDEA 2017
  • JDK版本:jdk 1.8
  • Maven版本:apache-maven-3.5.0
  • SpringBoot版本:SpringBoot 2.0

二、pom依赖文件

<?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.lonelycountry</groupId>
	<artifactId>springboot_02_scheduling_tasks</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot_02_scheduling_tasks</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

复制代码

三、相关代码

1、结构

2、代码

Application层

package com.lonelycountry;

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

@EnableScheduling
@SpringBootApplication
public class Springboot02SchedulingTasksApplication {

	public static void main(String[] args) {
	    SpringApplication.run(Springboot02SchedulingTasksApplication.class, args);
	}
}

复制代码

解读:
Application启动类中加入@EnableScheduling注解,就会启动定时服务。

工具层

package com.lonelycountry.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author YeFan
 * 2018/4/22.
 */
public class DateUtil {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static LocalDateTime parse(String text) {
        return LocalDateTime.parse(text, DATE_TIME_FORMATTER);
    }

    public static String format(LocalDateTime temporal) {
        return DATE_TIME_FORMATTER.format(temporal);
    }
}

复制代码

说明:
使用了在JDK1.8的新增加的日期类LocalDateTime和时间解析类DateTimeFormatter替换了DateSimpleDateFormat,原因是SimpleDateFormat在高并发的情况下调用parse()format()方法时会有几率出现异常,所以在JDK1.8中增加了DateTimeFormatter来替代它。

Task层

package com.lonelycountry.task;

import com.lonelycountry.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author YeFan
 * 2018/4/4.
 */
@Component
public class ScheduledTasks {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledTasks.class);

    /**
     * 上一次开始执行时间点之后5秒再执行
     */
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        LOGGER.info("the time is now {}", DateUtil.format(LocalDateTime.now()));
    }

    /**
     * 上一次执行完毕时间点之后5秒再执行
     */
    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTime1() {
        LOGGER.info("the time is now {}", DateUtil.format(LocalDateTime.now()));
    }

    /**
     * 上一次执行完毕时间点之后5秒再执行
     */
    @Scheduled(initialDelay = 1000, fixedDelay = 5000)
    public void reportCurrentTime2() {
        LOGGER.info("the time is now {}", DateUtil.format(LocalDateTime.now()));
    }

    /**
     * 从0秒开始,每三十秒执行一次
     */
    @Scheduled(cron="0/30 * * * * ?")
    public void reportCurrentTime3() {
        LOGGER.info("the time is now {}", DateUtil.format(LocalDateTime.now()));
    }

    /**
     * 从10秒开始,每三十秒执行一次
     */
    @Scheduled(cron="10/30 * * * * ?")
    public void reportCurrentTime4() {
        LOGGER.info("the time is now {}", DateUtil.format(LocalDateTime.now()));
    }

    /**
     *  从1日开始,每5天执行一次
     */
    @Scheduled(cron="* * * 1/5 * ? ")
    public void reportCurrentTime5() {
        LOGGER.info("the time is now {}", DateUtil.format(LocalDateTime.now()));
    }

}

}
复制代码

说明:

  1. 记得给Task类加上@Component注解。
  2. 给需要定时执行的方法上面加上@Scheduled参数,并填对应的参数。
  3. 支持cron表达式,推荐个工具网站

四、代码地址及参考文档

源代码
Scheduling Tasks

五、说明

本文为原创,转载请注明原处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值