SpringBoot入门八,添加定时任务

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入门八,添加定时任务

猜你喜欢

转载自blog.51cto.com/1197822/2295894