当前位置: 首页 > 编程日记 > 正文

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也两个重要的内部类:DelayedWorkQueueScheduledFutureTask。可以看出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时&#xff0c;即为各个向量的元素绝对值之和 >> norm(x,1)ans 21>> xx 1 2 3 4 5 6>> no…

如何打一个FatJar(uber-jar)

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

JDK源码分析 NIO实现

总列表&#xff1a;http://hg.openjdk.java.net/ 小版本&#xff1a;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&#xff0c;先要知道进程ID的类型&#xff1a; 内核中进程ID的类型用pid_type来描述,它被定义在include/linux/pid.h中 enum pid_type {PIDTYPE_PID,PIDTYPE_PGID,PIDTYPE_SID,PIDTYPE_MAX };12345671234567PID 内核…

【MATLAB】矩阵运算之矩阵分解

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

Java入门—输入输出流

File类的使用 文件是&#xff1a;文件可认为是相关记录或放在一起的数据的集合。 Java中&#xff0c;使用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 这是许多执行基本任务&#xff08;例如JSON序列化&#xff0c;数据库访问和服务器端模板组成&#xff09;的Web应用程序框架的性能比较。每个框架都在实际的生产配置中运行。结果在云实例和物理硬件上捕获。测试实现主要是由社区贡献的&#xff0c;所…

vsftpd用户配置 No.2

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

【MATLAB】稀疏矩阵(含有大量0元素的矩阵)

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

httpTomcat

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

memcached(二)事件模型源码分析

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

【MATLAB】MATLAB的控制流

1、if-else-end if expressioncommands1 elseif expression2commands2 ... else commandsn end 2、switch-case switch valuecase1 test1%如果value等于test1&#xff0c;执行command1&#xff0c;并结束此结构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

普通查询 某个字段匹配数组内的元素数量的&#xff0c;假如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题 车灯线光源的优化设计 安装在汽车头部的车灯的形状为一旋转抛物面&#xff0c;车灯的对称轴水平地指向正前方, 其开口半径36毫米&#xff0c;深度21.6毫米。经过车灯的焦点&#xff0c;在与对称轴相垂直的水平方向&#xff0c;对称地放置一定长度的均匀分布的线光源。要求…

从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&#xff0c;为什么DAPP生态需要自带钱包功能&#xff1f; 区块链是一个伟大的发明&#xff0c;它改变了生产关系。很多生态&#xff0c;有了区块链技术&#xff0c;可以由全公司员工的"全员合伙人"变成了全平台的”全体合伙人”了&#xff0c;是真正的共享经济模式…

为什么jdk源码推荐ThreadLocal使用static

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

C与C++之间相互调用

1、导出C函数以用于C或C的项目 如果使用C语言编写的DLL&#xff0c;希望从中导出函数给C或C的模块访问&#xff0c;则应使用 __cplusplus 预处理器宏确定正在编译的语言。如果是从C语言模块使用&#xff0c;则用C链接声明这些函数。如果使用此技术并为DLL提供头文件&#xff0c…

【MATLAB】三维图形的绘制mesh

步骤如下&#xff1a; &#xff08;1&#xff09;确定自变量x和y的取值范围和取值间隔 x x1 :dx :x2 , y y1 : dy : y2 &#xff08;2&#xff09;构成xoy平面上的自变量采样“格点”矩阵 ①利用格点矩阵的原理生成矩阵。 xx1:dx:x2; yy1:dy:y2; Xones(size(y))*x; Yy*o…

ORA-01919: role 'PLUSTRACE' does not exist

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

Java反射以及应用

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

【MATLAB】雅可比矩阵jacobi matrix

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

Laravel:使用Migrations

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

基于libevent和unix domain socket的本地server

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

软件体系架构模式之一什么是软件架构模式

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

HP 服务器 iLO 远程控制软件 介绍

iLO了解&#xff1a;iLO 是一组芯片&#xff0c;内部是vxworks的嵌入操作系统,在服务器的背后有一个标准RJ45口对外连接生产用交换机或者带外管理的交换机。iLO 全名是 Integrated Lights-out&#xff0c;它是惠普某些型号的服务器上集成的远程管理端口&#xff0c;它能够允许用…

【MATLAB】数据分析之数据插值

插值&#xff1a;求过已知有限个数据点的近似函数。 区别于拟合&#xff1a; 拟合&#xff1a;已知有限个数据点求近似函数&#xff0c;不要求过已知数据点&#xff0c;只要求在某种意义下它在这些点上的总偏差最小。 基本常用的插值方法&#xff1a;拉格朗日多项式插值&…

迈斯!啊呸~数学

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; } 乘法逆元&#xff08;保证模域p与求逆元的数互质&#xff09; po(a,p-2);//a为需要求逆元的数 扩展欧几里得&#xff08;exgcd&#xff09; #include<cstdio&g…