1、增加开启注解

//开启定时任务
@EnableScheduling
//开启异步调用方法
@EnableAsync
public class SpringBootStarterApplication {

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

}

2、创建任务类

@Component
public class TestTask {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    //定义每过3秒执行任务
    @Scheduled(fixedRate = 3000)
    //@Scheduled(cron = "4-40 * * * * ?")
    public void reportCurrentTime() {
        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }
}

一些解释

  1. fixedRate:如果任务的处理时间大于fixedRate配置的时间,那么当任务结束的时候则会立马执行。如果是在相隔的时间段内处理完毕,假设设置的是5s,任务花了3s执行完毕,那么在2s后则会执行下一个任务。
  2. fixedDelay:如果设定的是相隔5s执行,当前任务假设需要花费8s,那么下一次的执行的时间为当前任务执行完毕后,相隔5s后再执行。

标签: none

添加新评论