参考:SpringBoot开启注解调用定时任务
    SpringBoot使用@Scheduled注解实现定时任务
    可通过在线生成Cron表达式的工具:http://cron.qqe2.com/ 来生成自己想要的表达式。
    1)开启定时任务
    SpringBoot 项目在项目启动类上添加 @EnableScheduling 注解即可开启定时任务管理。

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

    2)创建定时任务
    创建定时任务,并使用 @Scheduled 注解。

    1. package com.pjb.Schedule;
    2. import org.springframework.scheduling.annotation.Scheduled;
    3. import org.springframework.stereotype.Component;
    4. import java.text.SimpleDateFormat;
    5. import java.util.Date;
    6. /**
    7. * 定时任务的使用
    8. * @author pan_junbiao
    9. **/
    10. @Component
    11. public class Task
    12. {
    13. @Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次
    14. public void execute(){
    15. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置日期格式
    16. System.out.println("欢迎访问 pan_junbiao的博客 " + df.format(new Date()));
    17. }
    18. }