SpringBoot源码分析之@Scheduled
Springboot写上注解@Scheduled就可以实现定时任务,
这里对其源码做一点分析
@Service
public class MyScheduled {@Scheduled(cron="${time.cron}")void paoapaoScheduled() {System.out.println("Execute at " + System.currentTimeMillis());}
}
配置文件100秒一次
time.cron=*/100 * * * * *
重要的类ScheduledAnnotationBeanPostProcessor
@Nullableprivate BeanFactory beanFactory;
private void finishRegistration() {if (this.scheduler != null) {this.registrar.setScheduler(this.scheduler);}if (this.beanFactory instanceof ListableBeanFactory) {Map<String, SchedulingConfigurer> beans =((ListableBeanFactory) this.beanFactory).getBeansOfType(SchedulingConfigurer.class);List<SchedulingConfigurer> configurers = new ArrayList<>(beans.values());AnnotationAwareOrderComparator.sort(configurers);for (SchedulingConfigurer configurer : configurers) {configurer.configureTasks(this.registrar);}}if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {Assert.state(this.beanFactory != null, "BeanFactory must be set to find scheduler by type");try {// Search for TaskScheduler bean...this.registrar.setTaskScheduler(resolveSchedulerBean(this.beanFactory, TaskScheduler.class, false));}catch (NoUniqueBeanDefinitionException ex) {logger.trace("Could not find unique TaskScheduler bean", ex);try {this.registrar.setTaskScheduler(resolveSchedulerBean(this.beanFactory, TaskScheduler.class, true));}catch (NoSuchBeanDefinitionException ex2) {if (logger.isInfoEnabled()) {logger.info("More than one TaskScheduler bean exists within the context, and " +"none is named 'taskScheduler'. Mark one of them as primary or name it 'taskScheduler' " +"(possibly as an alias); or implement the SchedulingConfigurer interface and call " +"ScheduledTaskRegistrar#setScheduler explicitly within the configureTasks() callback: " +ex.getBeanNamesFound());}}}catch (NoSuchBeanDefinitionException ex) {logger.trace("Could not find default TaskScheduler bean", ex);// Search for ScheduledExecutorService bean next...try {this.registrar.setScheduler(resolveSchedulerBean(this.beanFactory, ScheduledExecutorService.class, false));}catch (NoUniqueBeanDefinitionException ex2) {logger.trace("Could not find unique ScheduledExecutorService bean", ex2);try {this.registrar.setScheduler(resolveSchedulerBean(this.beanFactory, ScheduledExecutorService.class, true));}catch (NoSuchBeanDefinitionException ex3) {if (logger.isInfoEnabled()) {logger.info("More than one ScheduledExecutorService bean exists within the context, and " +"none is named 'taskScheduler'. Mark one of them as primary or name it 'taskScheduler' " +"(possibly as an alias); or implement the SchedulingConfigurer interface and call " +"ScheduledTaskRegistrar#setScheduler explicitly within the configureTasks() callback: " +ex2.getBeanNamesFound());}}}catch (NoSuchBeanDefinitionException ex2) {logger.trace("Could not find default ScheduledExecutorService bean", ex2);// Giving up -> falling back to default scheduler within the registrar...logger.info("No TaskScheduler/ScheduledExecutorService bean found for scheduled processing");}}}this.registrar.afterPropertiesSet();}
bean
找到自定义的MyScheduled
这里先逆向找到可见代码,再往上找到他的赋值地方
if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {Assert.state(this.beanFactory != null, "BeanFactory must be set to find scheduler by type");try {// Search for TaskScheduler bean...this.registrar.setTaskScheduler(resolveSchedulerBean(this.beanFactory, TaskScheduler.class, false));}catch (NoUniqueBeanDefinitionException ex) {logger.trace("Could not find unique TaskScheduler bean", ex);try {this.registrar.setTaskScheduler(resolveSchedulerBean(this.beanFactory, TaskScheduler.class, true));}
重要类ScheduledThreadPoolExecutor
参考:https://www.jianshu.com/p/502f9952c09b
ScheduledThreadPoolExecutor继承了ThreadPoolExecutor
,也就是说ScheduledThreadPoolExecutor拥有execute()和submit()提交异步任务的基础功能,ScheduledThreadPoolExecutor类实现了ScheduledExecutorService
,该接口定义了ScheduledThreadPoolExecutor能够延时执行任务和周期执行任务的功能。
ScheduledThreadPoolExecutor也两个重要的内部类:DelayedWorkQueue和ScheduledFutureTask。可以看出DelayedWorkQueue实现了BlockingQueue接口,也就是一个阻塞队列,ScheduledFutureTask则是继承了FutureTask类,也表示该类用于返回异步任务的结果。
/*** @throws RejectedExecutionException {@inheritDoc}* @throws NullPointerException {@inheritDoc}*/public ScheduledFuture<?> schedule(Runnable command,long delay,TimeUnit unit) {if (command == null || unit == null)throw new NullPointerException();RunnableScheduledFuture<?> t = decorateTask(command,new ScheduledFutureTask<Void>(command, null,triggerTime(delay, unit)));delayedExecute(t);return t;}
到了schedule这里:
增加定时任务ScheduledTaskRegistrar
protected void scheduleTasks() {if (this.taskScheduler == null) {this.localExecutor = Executors.newSingleThreadScheduledExecutor();this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);}if (this.triggerTasks != null) {for (TriggerTask task : this.triggerTasks) {addScheduledTask(scheduleTriggerTask(task));}}if (this.cronTasks != null) {for (CronTask task : this.cronTasks) {addScheduledTask(scheduleCronTask(task));}}if (this.fixedRateTasks != null) {for (IntervalTask task : this.fixedRateTasks) {addScheduledTask(scheduleFixedRateTask(task));}}if (this.fixedDelayTasks != null) {for (IntervalTask task : this.fixedDelayTasks) {addScheduledTask(scheduleFixedDelayTask(task));}}}
遍历arrayList
跳出refresh
Spring如何添加钩子函数
这里没有注册钩子函数自然是null
进Runtime.getRuntime().addShutdownHook(this.shutdownHook);
终于完了
============================
触发定时
倒着看就知道怎么调用的,实际上是反射执行上述方法的:
invoke方法用来在运行时动态地调用某个实例的方法
这里实行了Runnable 接口:
反射,线程,线程池 底层还是这些技术!需要好好研究这块代码,加深理解基本原理。
扩展信息:SpringBoot中定时任务默认是串行执行 如何设置并行
SpringBoot 使用@Scheduled注解配置串行、并行定时任务
Spring Boot 中实现定时任务的两种方式
相关文章:
【MATLAB】矩阵分析之向量和矩阵的范数运算
本片借鉴于 https://blog.csdn.net/u013534498/article/details/52674008 https://blog.csdn.net/left_la/article/details/9159949 向量范数当p1时,即为各个向量的元素绝对值之和 >> norm(x,1)ans 21>> xx 1 2 3 4 5 6>> no…

如何打一个FatJar(uber-jar)
如何打一个FatJar(uber-jar) FatJar也就叫做UberJar,是一种可执行的Jar包(Executable Jar)。FatJar和普通的jar不同在于它包含了依赖的jar包。 1. maven-jar-plugin 例子 <build><finalName>demo</finalName><plugins&g…

JDK源码分析 NIO实现
总列表:http://hg.openjdk.java.net/ 小版本:http://hg.openjdk.java.net/jdk8u jdk:http://hg.openjdk.java.net/jdk8u/jdk8u60/file/d8f4022fe0cd hotspot:http://hg.openjdk.java.net/jdk8u/jdk8u60/hotspot/file/37240c1019fd 调用本地native方法…
Linux进程ID号--Linux进程的管理与调度(三)
进程ID概述 进程ID类型 要想了解内核如何来组织和管理进程ID,先要知道进程ID的类型: 内核中进程ID的类型用pid_type来描述,它被定义在include/linux/pid.h中 enum pid_type {PIDTYPE_PID,PIDTYPE_PGID,PIDTYPE_SID,PIDTYPE_MAX };12345671234567PID 内核…

【MATLAB】矩阵运算之矩阵分解
矩阵分解:把一个矩阵分解成为矩阵连乘的形式。矩阵的分解函数cholCholesky分解cholinc稀疏矩阵的不完全Cholesky分解lu矩阵LU分解luinc稀疏矩阵的不完全LU分解qr正交三角分解svd奇异值分解gsvd一般奇异值分解schur舒尔分解 在MATLAB中线性方程组的求解主要基于四种基…

Java入门—输入输出流
File类的使用 文件是:文件可认为是相关记录或放在一起的数据的集合。 Java中,使用java.io.File类对文件进行操作 public class FileDemo {public static void main(String[] args) {String path "E:\\pdd";File f new File(path);//判断是文…

Web框架基准测试
Web Framework Benchmarks 这是许多执行基本任务(例如JSON序列化,数据库访问和服务器端模板组成)的Web应用程序框架的性能比较。每个框架都在实际的生产配置中运行。结果在云实例和物理硬件上捕获。测试实现主要是由社区贡献的,所…

vsftpd用户配置 No.2
在配置ftp虚拟用户的过程中,还有一种配置方式。yum -y install 安装vsftpdcp /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.conf.bak编辑vsftpd.conf开启下列选项:anonymous_enableNOlocal_enableYESwrite_enableYESlocal_umask022anon_mkdir_write_enab…

【MATLAB】稀疏矩阵(含有大量0元素的矩阵)
1、稀疏矩阵的储存方式 对于稀疏矩阵,MATLAB仅储存矩阵所有非零元素的值及其位置(行号和列号)。 2、稀疏矩阵的生成 1)利用sparse函数从满矩阵转换得到稀疏矩阵函数名称表示意义sparse(A)由非零元素和下标建立稀疏矩阵A。如果A已是…

httpTomcat
Tomcat是web应用服务器的一种 转载于:https://juejin.im/post/5beaf7e451882517165d91d1

memcached(二)事件模型源码分析
在memcachedd中,作者为了专注于缓存的设计,使用了libevent来开发事件模型。memcachedd的时间模型同nginx的类似,拥有一个主进行(master)以及多个工作者线程(woker)。 流程图 在memcached中&…

【MATLAB】MATLAB的控制流
1、if-else-end if expressioncommands1 elseif expression2commands2 ... else commandsn end 2、switch-case switch valuecase1 test1%如果value等于test1,执行command1,并结束此结构command1case2 test2command2...case3 testkcommandk otherw…

Linux查看本机端口
查看指定的端口 # lsof -i:port 查看所有端口 # netstat -aptn 安装telnet #yum install -y telnet.x86_64 #telnet ip 端口

Node.js安装
通过nvm安装 下载nvm并执行wget -qO- https://raw.github.com/creationix/nvm/v0.33.11/install.sh | sh将命令输出到终端命令中~/.bashrcexport NVM_DIR"$HOME/.nvm"更新文件source .bashrc通过nvm安装node.jsnvm install 10.13安装的版本是10.13的版本 通过命令查看…

mongodb常用语句以及SpringBoot中使用mongodb
普通查询 某个字段匹配数组内的元素数量的,假如region只有一个元素的 db.getCollection(map).find({region:{$size:1}}) 假如region只有0个元素的 db.getCollection(map).find({region:{$size:0}}) db.getCollection(map).find({region:{$size:1}}).count() db.get…

2002高教社杯---A车灯线光源的优化设计
A题 车灯线光源的优化设计 安装在汽车头部的车灯的形状为一旋转抛物面,车灯的对称轴水平地指向正前方, 其开口半径36毫米,深度21.6毫米。经过车灯的焦点,在与对称轴相垂直的水平方向,对称地放置一定长度的均匀分布的线光源。要求…

从Date类型转为中文字符串
//主方法public static String DateToCh(Date date) {Calendar cal Calendar.getInstance();cal.setTime(date);int year cal.get(Calendar.YEAR);int month cal.get(Calendar.MONTH) 1;int day cal.get(Calendar.DAY_OF_MONTH);return getYear(year) getTenString(month…

第十四课 如何在DAPP应用实现自带钱包转账功能?
1,为什么DAPP生态需要自带钱包功能? 区块链是一个伟大的发明,它改变了生产关系。很多生态,有了区块链技术,可以由全公司员工的"全员合伙人"变成了全平台的”全体合伙人”了,是真正的共享经济模式…

为什么jdk源码推荐ThreadLocal使用static
ThreadLocal是线程私有变量,本身是解决多线程环境线程安全,可以说单线程实际上没必要使用。 既然多线程环境本身不使用static,那么又怎么会线程不安全。所以这个问题本身并不是问题,只是有人没有理解ThreadLocal的真正使用场景&a…

C与C++之间相互调用
1、导出C函数以用于C或C的项目 如果使用C语言编写的DLL,希望从中导出函数给C或C的模块访问,则应使用 __cplusplus 预处理器宏确定正在编译的语言。如果是从C语言模块使用,则用C链接声明这些函数。如果使用此技术并为DLL提供头文件,…
【MATLAB】三维图形的绘制mesh
步骤如下: (1)确定自变量x和y的取值范围和取值间隔 x x1 :dx :x2 , y y1 : dy : y2 (2)构成xoy平面上的自变量采样“格点”矩阵 ①利用格点矩阵的原理生成矩阵。 xx1:dx:x2; yy1:dy:y2; Xones(size(y))*x; Yy*o…

ORA-01919: role 'PLUSTRACE' does not exist
环境:Oracle 10g,11g.现象:在一次迁移测试中,发现有这样的角色赋权会报错不存在: SYSorcl> grant PLUSTRACE to jingyu; grant PLUSTRACE to jingyu* ERROR at line 1: ORA-01919: role PLUSTRACE does not exist 查询发现这个…

Java反射以及应用
需求:需要通过反射动态获取类的字段类型,然后做特殊处理 Java反射getDeclaredField和getField的区别 getDeclaredFiled 只能获取类本身的属性成员(包括私有、共有、保护) getField 仅能获取类(及其父类可以自己测试) public属性…

【MATLAB】雅可比矩阵jacobi matrix
参考页面: https://baike.baidu.com/item/%E9%9B%85%E5%8F%AF%E6%AF%94%E7%9F%A9%E9%98%B5/10753754?fraladdin#1 在向量微积分中,雅可比矩阵是一阶偏导数以一定方式排列成的矩阵,其行列式称为雅可比行列式。 由球坐标系到直角坐标系的转…

Laravel:使用Migrations
1、首先利用artisan创建一个可迁移的数据表模板,该命令运行后会在database/migrations目录下生成一个文件 php artisan make:migration create_fees_count_table --createfees_count 2、生成的文件包含up和down两个方法,其中up中是包含了添加表ÿ…

基于libevent和unix domain socket的本地server
https://www.pacificsimplicity.ca/blog/libevent-echo-server-tutorial 根据这一篇写一个最简单的demo。然后开始写client。 client调优 client最初的代码如下: 1 #include <sys/socket.h>2 #include <sys/un.h>3 #include <stdio.h>4 #include …

软件体系架构模式之一什么是软件架构模式
什么是软件架构模式 计划启动未开发的软件项目?然后选择正确的架构模式将对项目的结果起关键作用。选择市场上最流行或最新的技术并不总是意味着会带来最好的结果。但是,选择最合适的解决方案将为行之有效的问题和反复出现的问题提供可靠的解决方案。 …

HP 服务器 iLO 远程控制软件 介绍
iLO了解:iLO 是一组芯片,内部是vxworks的嵌入操作系统,在服务器的背后有一个标准RJ45口对外连接生产用交换机或者带外管理的交换机。iLO 全名是 Integrated Lights-out,它是惠普某些型号的服务器上集成的远程管理端口,它能够允许用…
【MATLAB】数据分析之数据插值
插值:求过已知有限个数据点的近似函数。 区别于拟合: 拟合:已知有限个数据点求近似函数,不要求过已知数据点,只要求在某种意义下它在这些点上的总偏差最小。 基本常用的插值方法:拉格朗日多项式插值&…

迈斯!啊呸~数学
1.数论 快速幂 int po(int x,int y) {int ans1;while(y){if(y%21)ans1ll*ans*x%p;x1ll*x*x%p;y/2;}return ans; } 乘法逆元(保证模域p与求逆元的数互质) po(a,p-2);//a为需要求逆元的数 扩展欧几里得(exgcd) #include<cstdio&g…