内容简介:我们在编写Spring Boot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信、邮件之类的操作,也可能会定时地检查和监控一些标志、参数等。(或者在张健博客定时刷一波评论(笑.jpg))在Spring Boot中编写定时任务是非常简单的事,下面通过实例介绍如何在Spring Boot中创建定时任务,实现每过5秒输出一下当前时间。
前言
我们在编写Spring Boot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信、邮件之类的操作,也可能会定时地检查和监控一些标志、参数等。(或者在张健博客定时刷一波评论(笑.jpg))
创建定时任务
在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);
}
测试
是不是很棒,很简单丫
第一次加载延迟指定时间后执行
第一次延迟30执行,之后按fixedRate的规则每10秒执行一次
@Scheduled(initialDelay = 30000,fixedDelay = 10000)
@Scheduled详解
在上面的入门例子中,使用了 @Scheduled(fixedRate = 5000) 注解来定义每过5秒执行的任务,对于 @Scheduled 的使用可以总结如下几种方式:
@Scheduled(fixedRate = 5000) @Scheduled(fixedDelay = 5000) @Scheduled(initialDelay=1000, fixedRate=5000) @Scheduled(cron="*/5 * * * * *")
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- SpringBoot与异步任务、定时任务、邮件任务
- 订阅 + 定时任务重构后台主机操作任务
- 宏任务和微任务的一个小事
- Yii2 定时任务创建(Console 任务)
- Yii2 定时任务创建(Console 任务)
- 了解js运行机制——微任务与宏任务
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。