springboot使用定时任务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nanruitao10/article/details/85293666

1.新建springboot项目,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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.channelsoft</groupId>
    <artifactId>springbootstudy</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootstudy</name>
    <description>Demo project for Spring Boot Study</description>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
                 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>


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

</project>

2.设置定时任务


@SpringBootApplication
@EnableScheduling
public class SpringbootstudyApplication {

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


}

3.编写任务类

@Component
@Slf4j
public class ScheduledTask {
	/**
	 * fixedRate的单位是毫秒
	 */
	@Scheduled(fixedRate = 100 * 30)
	public void testTask1() {
		log.info("启动第一个定时任务testTask1");
		log.info("Scheduling Tasks Examples: The time is now " + new Date());
	}

	@Scheduled(cron = "*/3 * * * * ?")
	public void testTask2() {
		log.info("启动第一个定时任务testTask2");
		log.info("Scheduling Tasks Examples: The time is now " + new Date());
	}

}

4.启动任务,查看结果

定时任务使用的springboot自带,如果你不想自己编写一下,可以clone:

GitHub地址:https://github.com/nanrt/springbootstudy.git

猜你喜欢

转载自blog.csdn.net/nanruitao10/article/details/85293666