SpringBoot定时任务

栏目: Java · 发布时间: 7年前

内容简介:我们在编写Spring Boot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信、邮件之类的操作,也可能会定时地检查和监控一些标志、参数等。(或者在张健博客定时刷一波评论(笑.jpg))在Spring Boot中编写定时任务是非常简单的事,下面通过实例介绍如何在Spring Boot中创建定时任务,实现每过5秒输出一下当前时间。

前言

我们在编写Spring Boot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信、邮件之类的操作,也可能会定时地检查和监控一些标志、参数等。(或者在张健博客定时刷一波评论(笑.jpg))

SpringBoot定时任务

创建定时任务

在Spring Boot中编写定时任务是非常简单的事,下面通过实例介绍如何在Spring Boot中创建定时任务,实现每过5秒输出一下当前时间。

  • 在Spring Boot的主类中加入 @EnableScheduling 注解,启用定时任务的配置

    /**

    * 开启定时任务

    */

    @SpringBootApplication

    @EnableScheduling

    public class GeccoApplication {

    public static void main(String[] args) {

    SpringApplication.run(GeccoApplication.class, args);

    }

    }

  • 创建定时任务实现类

方法注解@Scheduled

@Scheduled(fixedDelay = 10000)
public void schedule() {
  Stopwatch started = Stopwatch.createStarted();
  int id = 26;
  while (id > 0) {
  Futures.addCallback(guavaExecutor.submit(new Crawler(Integer.toString(id))), new FutureCallback<String>() {
  @Override
  public void onSuccess(String result) {
  System.out.println("任务结果:" + result);
  }

  @Override
  public void onFailure(Throwable t) {
  System.out.println("任务异常:" + t.getMessage());
  }
 }, executor);
  id--;
  }
  started.elapsed(TimeUnit.MILLISECONDS);
  LOGGER.info("执行时间:{}", dateFormat.format(new Date(System.currentTimeMillis())));
  String s = "CPU数:" + PROCESSORS + ", 当前线程:" + Thread.currentThread().getName() + ", 线程池中线程数目:" + executor.getPoolSize() + ",队列中等待执行的任务数目:" +
  executor.getQueue().size() + ",已执行玩别的任务数目:" + executor.getCompletedTaskCount();
  LOGGER.info(s);
}

测试

SpringBoot定时任务

SpringBoot定时任务

是不是很棒,很简单丫 SpringBoot定时任务

第一次加载延迟指定时间后执行

第一次延迟30执行,之后按fixedRate的规则每10秒执行一次

@Scheduled(initialDelay = 30000,fixedDelay = 10000)

SpringBoot定时任务

@Scheduled详解

在上面的入门例子中,使用了 @Scheduled(fixedRate = 5000) 注解来定义每过5秒执行的任务,对于 @Scheduled 的使用可以总结如下几种方式:

@Scheduled(fixedRate = 5000)
@Scheduled(fixedDelay = 5000)
@Scheduled(initialDelay=1000, fixedRate=5000)
@Scheduled(cron="*/5 * * * * *")

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

深入应用C++11

深入应用C++11

祁宇 / 机械工业出版社 / 2015-5 / 79

在StackOverflow的最近一次世界性调查中,C++11在所有的编程语言中排名第二, C++11受到程序员的追捧是毫不意外的,因为它就像C++之父Bjarne Stroustrup说的:它看起来就像一门新的语言。C++11新增加了相当多的现代编程语言的特性,相比C++98/03,它在生产力、安全性、性能和易用性上都有了大幅提高。比如auto和decltype让我们从书写冗长的类型和繁琐的类型......一起来看看 《深入应用C++11》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换