spingboot @EnableScheduling

Posted jtlgb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spingboot @EnableScheduling相关的知识,希望对你有一定的参考价值。

springboot让开发更简单!springmvc中启用定时任务还得需要在xml中进行配置启用并且要配置扫描器,但是springboot只需要一个注解就可以。

@EnableScheduling

无需多余的jar依赖,所以pom不贴了

applaction.java

  1. package com.sbm;
  2.  
  3.  import org.springframework.boot.SpringApplication;
  4.  import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  import org.springframework.scheduling.annotation.EnableScheduling;
  6.   
  7.  @SpringBootApplication
  8.  @EnableScheduling
  9.  public class Application {
  10.   
  11.  public static void main(String[] args) {
  12.  SpringApplication.run(Application.class, args);
  13.  }
  14.  }



定时任务类AppCoreTask.java

  1.  package com.sbm.scheduling;
  2.   
  3.  import org.springframework.scheduling.annotation.Scheduled;
  4.  import org.springframework.stereotype.Component;
  5.  import java.util.Date;
  6.   
  7.  @Component
  8.  public class AppCoreTask {
  9.   
  10.  @Scheduled(cron = "0 53 15 * * ? ")
  11.  public void tesk() {
  12.  System.out.print("开启定时任务" + new Date());
  13.  }
  14.  }



要求在15:53分打印一句话

关于cron表达式的用法,可以在我的这篇文章里查看:Spring Task 中cron表达式整理记录

运行sb程序


  1.  
    016-12-30 15:52:24.653 INFO 4204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  2.  
    2016-12-30 15:52:24.654 INFO 4204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  3.  
    2016-12-30 15:52:24.722 INFO 4204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  4.  
    2016-12-30 15:52:25.183 INFO 4204 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
  5.  
    2016-12-30 15:52:25.212 INFO 4204 --- [ main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
  6.  
    2016-12-30 15:52:25.315 INFO 4204 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
  7.  
    2016-12-30 15:52:25.326 INFO 4204 --- [ main] com.sbm.Application : Started Application in 7.124 seconds (JVM running for 8.234)
  8.  
    开启定时任务Fri Dec 30 15:53:00 CST 2016
  9.  





以上是关于spingboot @EnableScheduling的主要内容,如果未能解决你的问题,请参考以下文章

spingboot @EnableScheduling

spingBoot-自定义过滤器

SpingBoot注解

spingboot集成jpa

SpingBoot学习之启动方式

Mybatis和spingboot整合