1. package com.lyd.swagger;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.scheduling.annotation.EnableAsync;
    5. import org.springframework.scheduling.annotation.EnableScheduling;
    6. @EnableScheduling //启动定时任务
    7. @SpringBootApplication
    8. public class SwaggerApplication {
    9. public static void main(String[] args) {
    10. SpringApplication.run(SwaggerApplication.class, args);
    11. }
    12. }

    不用刻意去调用下面的hello方法,加了@Scheduled注解,到时间了自动调用

    1. package com.lyd.swagger.service;
    2. import org.springframework.scheduling.annotation.Scheduled;
    3. import org.springframework.stereotype.Service;
    4. @Service
    5. public class ScheduledService {
    6. //在一个特定的时间执行这个方法
    7. //cron表达式,用来表示在什么时间执行,有点反人类,网上有很多教程
    8. //秒 分 时 日 月 周几
    9. @Scheduled(cron="0 31 10 * * ?")
    10. public void hello(){
    11. System.out.println("hello,这里被执行了");
    12. }
    13. }

    cron表达式详解,cron表达式写法,cron表达式例子 cron表达式生成器