线程池之 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 ...
随机推荐
- hadoop MapReduce —— 输出每个单词所对应的文件
下面是四个文件及其内容. 代码实现: Mapper: package cn.tedu.invert; import java.io.IOException; import org.apache.had ...
- HDOJ 2005 第几天?
#include<iostream> using namespace std; ] = { ,,,,,,,,,,, }; ] = { ,,,,,,,,,,, }; bool isRYear ...
- 禅道在docker上部署与迁移
一.禅道部署 1.下载地址 禅道开源版: http://dl.cnezsoft.com/zentao/docker/docker_zentao.zip 数据库用户名: root,默认密码: 123 ...
- [UE4]给Widget增加参数,Pre Construct和Construct的区别
使用Pre Construct事件可以在编辑器中实时显示出选择的背景图片. 如果使用的是“Construct”事件则只能在游戏运行时把图片显示出来.
- 关于在Intellij IDEA工具中配置热加载问题
第一步,创建一个maven项目,然后在pom.xml文件中添加依赖(上图内容). 第二步:来到intellij idea主页面,点击File->Settings->Build->co ...
- Unreal Engine 4 Based Materials
转自:http://www.52vr.com/article-862-1.html 材质参数 UE4的材质参数有4个,输入范围都是0~1之间……分别为: Base Color Roughnes ...
- lightgbm的sklearn接口和原生接口参数详细说明及调参指点
class lightgbm.LGBMClassifier(boosting_type='gbdt', num_leaves=31, max_depth=-1, learning_rate=0.1, ...
- POI实现导出Excel和模板导出Excel
一.导出过程 1.用户请求导出 2.先访问数据库,查询需要导出的结果集 3.创建导出的Excel工作簿 4.遍历结果集,写入工作簿 5.将Excel已文件下载的形式回复给请求客户端 二.具体实现(截取 ...
- 如何使用webpack打包项目
webpack是前端开发中比较常用的打包工具之一,另外还有gulp,grunt.之前没有涉及过打包这块,这里介绍一下使用webpack打包的流程. Grunt和Gulp的工作方式是:在一个配置文件中, ...
- window自带的公式面板
如何使用Windows数学输入面板生成数学公式 数学输入面板是一个Windows自带的数学公式编辑软件,该软件最大的特点就是可以简单方便地写出数学公式.本文主要探讨该软件的一些基本用法. 工具/原料 ...