线程池之 newScheduledThreadPool中scheduleAtFixedRate(四个参数)
转自:https://blog.csdn.net/weixin_35756522/article/details/81707276
说明:在处理消费数据的时候,统计tps,需要用一个线程监控来获得tps值,则使用了定时任务的线程池中的方法
scheduleAtFixedRate(),此方法有四个参数
一:简单说明
ScheduleExecutorService接口中有四个重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比较方便。
下面是该接口的原型定义
java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executor

接口scheduleAtFixedRate原型定义及参数说明
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit);
command:执行线程
initialDelay:初始化延时
period:两次开始执行最小间隔时间
unit:计时单位
接口scheduleWithFixedDelay原型定义及参数说明
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit);
command:执行线程
initialDelay:初始化延时
period:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
unit:计时单位
二:功能示例
1.按指定频率周期执行某个任务。
初始化延迟0ms开始执行,每隔100ms重新执行一次任务。
/*** 以固定周期频率执行任务*/public static void executeFixedRate() {ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);executor.scheduleAtFixedRate(new EchoServer(),0,100,TimeUnit.MILLISECONDS);}
间隔指的是连续两次任务开始执行的间隔。
2.按指定频率间隔执行某个任务。
初始化时延时0ms开始执行,本次执行结束后延迟100ms开始下次执行。
/*** 以固定延迟时间进行执行* 本次任务执行完成后,需要延迟设定的延迟时间,才会执行新的任务*/public static void executeFixedDelay() {ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);executor.scheduleWithFixedDelay(new EchoServer(),0,100,TimeUnit.MILLISECONDS);}
3.周期定时执行某个任务。
有时候我们希望一个任务被安排在凌晨3点(访问较少时)周期性的执行一个比较耗费资源的任务,可以使用下面方法设定每天在固定时间执行一次任务。
/*** 每天晚上8点执行一次* 每天定时安排任务进行执行*/public static void executeEightAtNightPerDay() {ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);long oneDay = 24 * 60 * 60 * 1000;long initDelay = getTimeMillis("20:00:00") - System.currentTimeMillis();initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;executor.scheduleAtFixedRate(new EchoServer(),initDelay,oneDay,TimeUnit.MILLISECONDS);}
/*** 获取指定时间对应的毫秒数* @param time "HH:mm:ss"* @return*/private static long getTimeMillis(String time) {try {DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);return curDate.getTime();} catch (ParseException e) {e.printStackTrace();}return 0;}
4.辅助代码
class EchoServer implements Runnable {@Overridepublic void run() {try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("This is a echo server. The current time is " +System.currentTimeMillis() + ".");}}
三:一些问题
上面写的内容有不严谨的地方,比如对于scheduleAtFixedRate方法,当我们要执行的任务大于我们指定的执行间隔时会怎么样呢?
对于中文API中的注释,我们可能会被忽悠,认为无论怎么样,它都会按照我们指定的间隔进行执行,其实当执行任务的时间大于我们指定的间隔时间时,它并不会在指定间隔时开辟一个新的线程并发执行这个任务。而是等待该线程执行完毕。
源码注释如下:
* Creates and executes a periodic action that becomes enabled first* after the given initial delay, and subsequently with the given* period; that is executions will commence after* <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then* <tt>initialDelay + 2 * period</tt>, and so on.* If any execution of the task* encounters an exception, subsequent executions are suppressed.* Otherwise, the task will only terminate via cancellation or* termination of the executor. If any execution of this task* takes longer than its period, then subsequent executions* may start late, but will not concurrently execute.
根据注释中的内容,我们需要注意的时,我们需要捕获最上层的异常,防止出现异常中止执行,导致周期性的任务不再执行。
四:除了我们自己实现定时任务之外,我们可以使用Spring帮我们完成这样的事情。
Spring自动定时任务配置方法(我们要执行任务的类名为com.study.MyTimedTask)
<bean id="myTimedTask" class="com.study.MyTimedTask"/>
<bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"><property name="targetObject" ref="myTimedTask"/><property name="targetMethod" value="execute"/><property name="concurrent" value="false"/></bean>
<bean id="myTimedTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"><property name="jobDetail" ref="doMyTimedTask"/><property name="cronExpression" value="0 0 2 * ?"/></bean>
<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><property name="triggers"><list><ref local="myTimedTaskTrigger"/></list></property></bean>
<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><property name="triggers"><list><bean class="org.springframework.scheduling.quartz.CronTriggerBean"><property name="jobDetail"/><bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"><property name="targetObject"><bean class="com.study.MyTimedTask"/></property><property name="targetMethod" value="execute"/><property name="concurrent" value="false"/></bean></property><property name="cronExpression" value="0 0 2 * ?"/></bean></list></property></bean>
线程池之 newScheduledThreadPool中scheduleAtFixedRate(四个参数)的更多相关文章
- 线程池是什么?Java四种线程池的使用介绍
使用线程池的好处有很多,比如节省系统资源的开销,节省创建和销毁线程的时间等,当我们需要处理的任务较多时,就可以使用线程池,可能还有很多用户不知道Java线程池如何使用?下面小编给大家分享Java四种线 ...
- 线程池与Python中的GIL
线程池是一个操作系统的概念,它是对多线程的一种优化. 多线程的时候,创建和销毁线程伴随着操作系统的开销,如果频繁创建/销毁线程,则会使效率大大降低. 而线程池,是先创建出一批线程放入池子里,需要创建线 ...
- python---基础知识回顾(十)进程和线程(py2中自定义线程池和py3中的线程池使用)
一:自定义线程池的实现 前戏: 在进行自定义线程池前,先了解下Queue队列 队列中可以存放基础数据类型,也可以存放类,对象等特殊数据类型 from queue import Queue class ...
- java手写线程池,完善中
package com.test001.threadpool; import java.util.LinkedList; import java.util.List; import java.util ...
- 线程池构造类 ThreadPoolExecutor 的 5 个参数
1.corePoolSize :核心线程数 2.maxPoolSize: 最大线程数 3.keepAliveTime :闲置线程存活时间 4.unit:参数keepAliveTime的时间单位,有7种 ...
- Java编程的逻辑 (78) - 线程池
本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...
- Java 四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor
介绍new Thread的弊端及Java四种线程池的使用,对Android同样适用.本文是基础篇,后面会分享下线程池一些高级功能. 1.new Thread的弊端执行一个异步任务你还只是如下new T ...
- Java四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor
1.new Thread的弊端 执行一个异步任务你还只是如下new Thread吗? Java new Thread(new Runnable() { @Override public void ru ...
- Java四种线程池
Java四种线程池newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor 时间:20 ...
随机推荐
- springboot(整合多数据源demo,aop,定时任务,异步方法调用,以及获取properties中自定义的变量值)
有这么一个需求 每个部门,需要操作的数据库不同,A部门要将数据放test数据库,B 部门数据 要放在test1数据库 同一个项目 需要整合 多个数据源 上传个demo 方便自己以后回看!!!!!!!! ...
- linux一些基本知识
一.linux i386是32位的,amd64是64位(一般情况不限intel或者amd) server是服务器版,desktop是桌面版 Desktop是社区开源版,拥有一些新功能新软件 ...
- 廖雪峰Java3异常处理-1错误处理-2捕获异常
1捕获异常 1.1 finally语句保证有无错误都会执行 try{...}catch (){...}finally{...} 使用try...catch捕获异常 可能发生异常的语句放在try{... ...
- 构建Redis主从镜像
构建Redis的基础镜像,然后基于这个基础镜像构建主Redis镜像和从Redis镜像. 1.构建Redis基础镜像 创建redis基础镜像目录 [root@localhost mnt]# mkdir ...
- DrawerLayout 使用
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.Drawe ...
- 0001 - Spring MVC中的注解
1.概述 Spring MVC框架提供了功能强大的注解,大大简化了代码开发的同时也提升了程序的可扩展性 2.注解 2.1.@RequestMapping Spring MVC通过@RequestMap ...
- C# 知识特性 Attribute,XMLSerialize,
C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用“反射”查询特性,获取特性集合方 ...
- front-end architecture
这些东西都需要管理,并且提供一种比较好的方案去维护.在JavaScript被模块化之后,也可以通过单元测试来控制它们的质量,并且把这个过程自动化,每次版本有变更之前,保证它们最基本的正确性.最终,需要 ...
- 2-java内省机制(Introspector)
来一个简单的示例吧 package com.my.test; import java.beans.BeanInfo; import java.beans.Introspector; import ja ...
- 第6章 静态路由和动态路由(4)_OSPF动态路由协议
6. OSPF动态路由协议 6.1 OSPF协议(Open Shortest Path First,OSPF开放式最短路径优先协议) (1)通过路由器之间通告链路的状态来建立链路状态数据库,网络中所有 ...