怎么在springboot中使用@Scheduled实现一个定时任务

怎么在springboot中使用@Scheduled实现一个定时任务?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

创新互联建站自2013年起,先为东阿等服务建站,东阿等地企业,进行企业商务咨询服务。为东阿企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

1、pom.xml中导入必要的依赖:


    org.springframework.boot
    spring-boot-starter-parent
    2.0.1.RELEASE
  

  
    
    
      org.springframework.boot
      spring-boot-starter-web
    
    
      org.springframework.boot
      spring-boot-starter-tomcat
    
  

2、写一个springboot的启动类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
@ComponentScan(basePackages = { "com.xwj.tasks" })
@EnableScheduling // 开启定时任务
@EnableAutoConfiguration
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }
}

注意这里一定要加上@EnableScheduling注解,用于开启定时任务

3、开始写定时任务:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduleTask {
  @Scheduled(fixedRate = 1000)
  // @Scheduled(cron = "0 23-25 18 * * ?")
  public void testSchedule() {
    System.out.println("定时任务:" + System.currentTimeMillis());
  }
}

解释:

@Scheduled注解:

1、fixedRate 以固定速率执行。以上表示每隔1秒执行一次

2、fixedDelay 以上一个任务开始时间为基准,从上一任务开始执行后再次调用

3、cron表达式。可以实现定时调用。

关于怎么在springboot中使用@Scheduled实现一个定时任务问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


当前名称:怎么在springboot中使用@Scheduled实现一个定时任务
本文路径:http://bzwzjz.com/article/pepdop.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 专业网站设计 响应式网站设计 成都网站制作 成都网站建设推广 移动手机网站制作 重庆企业网站建设 梓潼网站设计 高端网站设计 成都响应式网站建设公司 手机网站建设套餐 成都网站建设 网站建设费用 泸州网站建设 成都网站建设 成都品牌网站设计 营销型网站建设 专业网站建设 成都营销网站建设 外贸网站建设 定制网站设计 网站设计 定制网站建设多少钱