0    课程地址

https://www.imooc.com/video/16734/0

 

1    本节重点
1.1  定时任务需要配置

顶类开启定时任务注解@EnableScheduling

定时任务类定义跑批间隔时间 @Scheduled(fixedRate = 3000)

 

2    课程demo
2.1  课程demo

顶类:

package com.example.demo;

import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication

//扫描mybaties mapper包路径
@MapperScan(basePackages = "com.example.demo.mapper")

//扫描 所需要的包,包含自用的工具类包所在路径
@ComponentScan(basePackages={"com.example.demo","org.n3r.idworker"})

//开启定时任务
@EnableScheduling
public class DemoApplication {

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

}

 

定时任务类:

package com.example.demo.task;

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

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * TestTask
 *
 * @author 魏豆豆
 * @date 2020/12/27
 */
//标注Spring管理的Bean,使用@Component注解在一个类上,表示将此类标记为Spring容器中的一个Bean。
@Component
public class TestTask {

    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

    //定义每3秒执行任务
    @Scheduled(fixedRate = 3000)
    public void printCurrentTime(){
        System.out.println("当前时间为:"+simpleDateFormat.format(new Date()));
    }
}

 

测试结果:

 

posted on 2020-12-27 07:30  菜鸟乙  阅读(89)  评论(0编辑  收藏  举报