SpringBoot中执行定时任务

一:在SpringBoot中使用定时任务相当的简单。首先,我们在启动类中加入@EnableScheduling来开启定时任务。

1 @SpringBootApplication
2 @EnableScheduling//允许定时任务
3 public class DemoApplication {
4 
5     public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }
6 
7 
8 }

二:创建实现定时任务的Service即可 。

//定时任务管理器
@Component
public class QuartzService {
    @Autowired
    MemberRepository memberRepository;
    @Autowired
    MemberRepository2 memberRepository2;

    //    每分钟启动
    @Scheduled(cron = "0 0/1 * * * ?")
    public void timerToNow() {
        System.out.println("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

}

 

补充知识:

cron表达式详解---https://www.cnblogs.com/javahr/p/8318728.html

在线生成Cron表达式---http://cron.qqe2.com/

 

posted @ 2018-09-21 17:07  179朱柏铭  阅读(157)  评论(0编辑  收藏  举报