SpringBoot @Scheduled 定时任务 入门demo

项目结果:

SpringBoot @Scheduled 定时任务 入门demo_第1张图片

1、     项目所需的jar包,因为是SpringBoot的demo,所以这里只需要引入spring-boot-starter-parent和spring-boot-starter-web即可。

pom.xml:



    4.0.0

    com.springboot
    scheduled-demo
    0.0.1-SNAPSHOT
    jar

    scheduled-demo
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.6.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



1、启动类:加上@EnableScheduling,这样才会去扫描@Scheduled的方法,去掉之后@Scheduled的方法将不会被执行。

package com.springboot.scheduleddemo;

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

@SpringBootApplication
@EnableScheduling
public class ScheduledDemoApplication {

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

2、写定时任务:

参考:在线Cron表达式

@Scheduled() 注解中写入Cron表达式。

此处将类加上@Component注解或者@Service均可。

"0/1 * * * * ? "表示每秒执行一次

package com.springboot.scheduleddemo.service;

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

import java.util.Date;

/**
 * @author: Lucifer
 * @create: 2018-10-29 22:39
 * @description:
 **/
@Component
public class ScheduledService {

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

}

控制台:

SpringBoot @Scheduled 定时任务 入门demo_第2张图片

3、加入SayNo方法

@Scheduled(cron = "0/1 * * * * ? ")
    public void sayNo(){
        System.out.println("定时任务2"+new Date()+".......No");
    }

此时启动,会看到控制台如下图:此时是同步的,串行,先执行sayHello,再执行SayNo.

SpringBoot @Scheduled 定时任务 入门demo_第3张图片

4、加上@Async

@SpringBootApplication
@EnableScheduling
@Async
public class ScheduledDemoApplication {

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

再次查看控制台:如图

此时不再是按顺序去执行了,而是异步。在启动类加上@Async,表示执行的是异步的

SpringBoot @Scheduled 定时任务 入门demo_第4张图片

你可能感兴趣的:(SpringBoot技术篇)