首页 > 编程语言 > 详细

SpringBoot入门八,添加定时任务

时间:2018-10-08 16:32:02      阅读:170      评论:0      收藏:0      [点我收藏+]

SpringBoot添加定时任务非常简单,只需要两步即可

1. SpringBoot启动类 添加@EnableScheduling注解,开启定时任务的配置

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

/**
 * <h5>描述:springboot启动类</h5>
 */
@SpringBootApplication
@EnableScheduling   // 开启定时任务的配置
public class DemoApp {
    public static void main(String[] args) {
        // 整个程序入口,启动springboot项目
        SpringApplication.run(DemoApp.class, args);
    }
}

2. 编写定时任务类

注意在类上不要少了注解,要执行的方法上也不能少了注解,@Scheduled的使用方法请找度娘

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

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

@Component
public class TaskTest {
    //输出时间格式
    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    // 第一次执行前延时5秒启动,每次任务结束后15秒再次启动
    @Scheduled(initialDelay = 5000, fixedDelay = 15000)
    private void sayHello() {
        System.out.println(format.format(new Date())+"向宇宙发出了一声问候:Hello World!");
    }
}

效果

技术分享图片

SpringBoot入门八,添加定时任务

原文:http://blog.51cto.com/1197822/2295894

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!