Spring Boot定时器

1.添加注解

@Component//定义Spring管理bean

@EnableScheduling//启动计划任务

2.执行计划

(1)@Scheduled(fixedRate=5000)//五秒执行一次

(2)@Scheduled(cron="0 33 13 ? * *")//指定时间启动任务

3.代码 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component// 定义Spring管理Bean
@EnableScheduling//启动计划任务
public class TestTask {
    private static final Logger logger = LoggerFactory.getLogger(TestTask.class);
    private static final SimpleDateFormat dataFormat=new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)//五秒执行一次
    public void reportCurrentTime(){
        logger.info("每隔五秒执行一次:"+dataFormat.format(new Date()));
    }

    @Scheduled(cron = "0 33 13 ? * *")//指点时间执行一次(13点33分)
    public void fixCurrentTime(){
        logger.info("在指点时间:"+dataFormat.format(new Date()));
    }
}

4.测试

猜你喜欢

转载自blog.csdn.net/zhaolinxuan1/article/details/83083284