SpringBoot Schedule 配置
1. 定时任务实现方式
定时任务实现方式:
- Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。一般用的较少,这篇文章将不做详细介绍。
- 使用Quartz,这是一个功能比较强大的的调度器,可以让你的程序在指定时间执行,也可以按照某一个频度执行,配置起来稍显复杂,有空介绍。
- SpringBoot自带的Scheduled,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多,本文主要介绍。
定时任务执行方式:
- 单线程(串行)
- 多线程(并行)
2. 创建定时任务
package com.autonavi.task.test; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import com.autonavi.task.ScheduledTasks; @Component
public class ScheduledTest { private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class); @Scheduled(cron="0 0/2 * * * ?")
public void executeFileDownLoadTask() { // 间隔2分钟,执行任务
Thread current = Thread.currentThread();
System.out.println("定时任务1:"+current.getId());
logger.info("ScheduledTest.executeFileDownLoadTask 定时任务1:"+current.getId()+ ",name:"+current.getName());
}
}
@Scheduled 注解用于标注这个方法是一个定时任务的方法,有多种配置可选。cron支持cron表达式,指定任务在特定时间执行;fixedRate以特定频率执行任务;fixedRateString以string的形式配置执行频率。
3. 启动定时任务
@SpringBootApplication
@EnableScheduling
public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String[] args) { SpringApplication.run(App.class, args);
logger.info("start");
}
}
其中 @EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。
Springboot本身默认的执行方式是串行执行,也就是说无论有多少task,都是一个线程串行执行,并行需手动配置
4. 并行任务
继承SchedulingConfigurer类并重写其方法即可,如下:
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer { @Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
} @Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(100);
}
}
再次执行之前的那个Demo,会欣然发现已经是并行执行了!
4. 异步并行任务
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar; @Configuration
@EnableScheduling
@EnableAsync(
mode = AdviceMode.PROXY, proxyTargetClass = false,
order = Ordered.HIGHEST_PRECEDENCE
)
@ComponentScan(
basePackages = "hello"
)
public class RootContextConfiguration implements
AsyncConfigurer, SchedulingConfigurer {
@Bean
public ThreadPoolTaskScheduler taskScheduler()
{
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(20);
scheduler.setThreadNamePrefix("task-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
} @Override
public Executor getAsyncExecutor()
{
Executor executor = this.taskScheduler();
return executor;
} @Override
public void configureTasks(ScheduledTaskRegistrar registrar)
{
TaskScheduler scheduler = this.taskScheduler();
registrar.setTaskScheduler(scheduler);
}
}
在启动的main方法加入额外配置:
@SpringBootApplication
public class Application { public static void main(String[] args) throws Exception { AnnotationConfigApplicationContext rootContext =
new AnnotationConfigApplicationContext(); rootContext.register(RootContextConfiguration.class);
rootContext.refresh();
}
}
SpringBoot Schedule 配置的更多相关文章
- SpringBoot常用配置简介
SpringBoot常用配置简介 1. SpringBoot中几个常用的配置的简单介绍 一个简单的Spring.factories # Bootstrap components org.springf ...
- 在SpringBoot中配置aop
前言 aop作为spring的一个强大的功能经常被使用,aop的应用场景有很多,但是实际的应用还是需要根据实际的业务来进行实现.这里就以打印日志作为例子,在SpringBoot中配置aop 已经加入我 ...
- SpringBoot cache-control 配置静态资源缓存 (以及其中的思考经历)
昨天在部署项目时遇到一个问题,因为服务要部署到外网使用,中间经过了较多的网络传输限制,而且要加载arcgis等较大的文件,所以在部署后,发现页面loading需要很长时间,而且刷新也要重新从服务器下载 ...
- 补习系列(10)-springboot 之配置读取
目录 简介 一.配置样例 二.如何注入配置 1. 缺省配置文件 2. 使用注解 3. 启动参数 还有.. 三.如何读取配置 @Value 注解 Environment 接口 @Configuratio ...
- springboot +redis配置
springboot +redis配置 pom依赖 <dependency> <groupId>org.springframework.boot</groupId> ...
- SpringBoot之配置
回顾 SpringBoot之基础 配置文件 ① 两种全局配置文件(文件名是固定的) 配置文件放在src/main/resources目录或者类路径/config下 application.proper ...
- SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页
SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页 **SpringBoot+Mybatis使用Pagehelper分页插件自动分页,非常好用,不用在自己去计算和组装了. ...
- SpringBoot自动配置源码调试
之前对SpringBoot的自动配置原理进行了较为详细的介绍(https://www.cnblogs.com/stm32stm32/p/10560933.html),接下来就对自动配置进行源码调试,探 ...
- SpringBoot实战之SpringBoot自动配置原理
SpringBoot 自动配置主要通过 @EnableAutoConfiguration, @Conditional, @EnableConfigurationProperties 或者 @Confi ...
随机推荐
- sp_helpdb
语法 sp_helpdb [ [ @dbname= ] 'name' ] 参数 [@dbname=] 'name' 是要为其提供信息的数据库名称.name 的数据类型为 sysname,无默认值.如果 ...
- C#,C++修改vs文件模板,添加自定义代码版权版本信息
简单型的修改类似该路径下的模板文件即可(vs版本或安装路径不同路径可能不同) C#: 模板参数参考https://msdn.microsoft.com/zh-cn/library/eehb4faa.a ...
- android stduio 引入 .so
- 安卓 android ListView 数据填充
在android开发中ListView是比较常用的组件,它以列表的形式展示具体内容,并且能够根据数据的长度自适应显示.抽空把对ListView的使用做了整理,并写了个小例子,如下图. 列表的显示需要三 ...
- 夺命雷公狗-----React_native---3---react-native-cli的安装
我们用npm安装下react-native-cli,并用-g来全局安装,我们用命令 npm install -g react-native-cli 如果和下图一样即表示已安装成功:
- Mysql数据库的使用总结之ERROR 1146 (42S02)
在使用mysql数据库过程中,遇到了错误ERROR 1146 (42S02):Table doesn't exist,经过了两天,终于解决了这个问题.引起该错误的原因不同,对应的解决方法也不同.这里只 ...
- opencv的学习笔记5
总结原博文中的一些边缘检测算子和滤波器.(Canny算子, Sobel算子, Laplace算子以及Scharr滤波器) 首先,一般的边缘检测包括三个步骤: 1)滤波:边缘检测的算法主要是基于图像 ...
- eBox(stm32) 之中断结构
eBox的中断结构参考了mbed,和我们平时所用的中断结构有些差异,不容易理解,最近仔细看了底层代码,终于搞清楚了,总结一下 一 首先要要搞清楚的几个概念:类的静态成员,实例成员 ...
- 227 Entering Passive Mode (xxx,xxx,,xxx,xxx,x)
登录ftp时显示227 Entering Passive Mode (xxx,xxx,,xxx,xxx,x) 因为FTP有两种工作模式,PORT方式和PASV方式,中文意思为主动式和被动式 ,详细介绍 ...
- 霍尼韦尔FC400A与FC400B的区别
给霍尼韦尔官方打电话咨询了下,发现两者区别不大,唯一的区别是400B可以和主机联动,也就是主机关的时候,400B也可以自动关闭,不需要手动去关闭电源,这样非常方便. 本来官方是只有400A的时候,但是 ...