(四)配置定时器

springboot大大的简化了以往的spring对定时器的配置。现在配置定时器仅仅需要2步 :

1、在application启动类中添加注解@EnableScheduling 

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableScheduling
public class DemoApplication {

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

    @RequestMapping(value = "/")
    public  String defaultMapping(){
        return "welcome" ;
    }

}

 

2、配置定时器config的java类,指定执行频率和执行逻辑

package com.example.demo.javaConfig;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

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

@Configuration
public class ScheduleStandTest {

    // 表达式 秒 分 时 天 月 周 (周可用1-7表示,周日第一天 。也可以英文前3位SUN)
    @Scheduled(cron = "0 0/1 * * * ?")
    public void doExcute(){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String nowStr = sdf.format(new Date());
        System.out.println(nowStr);
    }
}

 

执行结果如下 

2019-11-22 10:22:00
2019-11-22 10:23:00
2019-11-22 10:24:00
2019-11-22 10:25:00
2019-11-22 10:26:00

 

 

posted @ 2019-11-21 16:44  残酷159  阅读(320)  评论(0)    收藏  举报