SpringBoot定时任务


参考自:​​https://www.dalaoyang.cn/article/19​

 

项目中很多时候会使用到定时任务,这篇文章介绍一下springboot整合定时任务。

springboot整合定时任务其实就两点,
  1.创建一个能被定时任务类,方法上加入@Scheduled注解
  2.在启动类application上加入@EnableScheduling注解

代码如下,pom文件我只加入了devtools,其实不加入也可以

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

<name>springboot_scheduled</name>
<description>springboot_scheduled</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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>

application类代码如下:

package com.example.demo;

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

@SpringBootApplication
@EnableScheduling
public class DemoApplication {

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

}

定时任务类TestTimer

package com.example.demo;

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

import java.util.Date;

/**
* @ Author wjw
* @ Date 2019-08-21
*/
@Component
public class TestTimer {

@Scheduled(cron = "0/1 * * * * ?")
public void test(){
System.out.println("执行定时任务的时间是:"+ new Date());
}

}

启动项目查看运行结果。

SpringBoot定时任务_maven

 

 需要注意的是@Scheduled(cron = “0/1 * * * * ?”)中cron的值根据自己实际需要去写,如果需要可以去下面的网站去弄。
​​​http://cron.qqe2.com/​

SpringBoot定时任务_spring_02

 

【版权声明】本博文著作权归作者所有,任何形式的转载都请联系作者获取授权并注明出处!

【重要说明】本文为本人的学习记录,论点和观点仅代表个人而不代表当时技术的真理,目的是自我学习和有幸成为可以向他人分享的经验,因此有错误会虚心接受改正,但不代表此刻博文无误!

【Gitee地址】秦浩铖:​​https://gitee.com/wjw1014​