线程池之 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 ...
随机推荐
- 【AMQ】之安装,启动,访问
1.访问官网下载AMQ 2.解压下载包 windows直接找到系统对应的win32|win64 双击activemq.bat 即可 linux执行 ./activemq start 访问: AMQ默认 ...
- 求1~n整数中1出现的次数(《剑指offer》面试题43)
题意: 给定一个整数n,求1~n这n个整数中十进制表示中1出现的次数. 思路: 方法1:最直观的是,对于1~n中的每个整数,分别判断n中的1的个数,具体见<剑指offer>.这种方法的时间 ...
- 高CPU排查方法分享
1 软件性能较差,占用CPU较多,往往是由于某段代码逻辑算法不佳导致,那如何在数以千计的函数中找到问题函数呢?2 在使用!runaway命令比较不同时间各线程占用CPU时间,找到CPU时间增涨较多的线 ...
- 面向对象php 接口 抽象类
1.定义类和实例化对象: 使用关键字class定义类,使用new实例化对象: 2.类成员的添加和访问: 类成员:有属性,方法,常量(常量名不带$符): 访问属性的时候,变量名不带$符 添加属性需要使用 ...
- centos7 firewall-cmd 理解多区域配置中的 firewalld 防火墙
原文:https://www.linuxidc.com/Linux/2017-11/148795.htm 现在的新闻里充斥着服务器被攻击和数据失窃事件.对于一个阅读过安全公告博客的人来说,通过访问错误 ...
- Spring Boot 学习视频
1. Spring Boot 项目实战 ----- 技术栈博客企业前后端 链接:https://pan.baidu.com/s/1hueViq4 密码:4ma8 2.Spring Boot 项目实 ...
- iis ajax post 跨域问题解决
iis ajax post时会遇到跨域的问题 只需要在IIS中http响应头中增加:Access-Control-Allow-Origin:*,即可解决问题
- Ribbon Workbench 与此流程相关的流程操作未激活
问题描述:使用Ribbon Workbench 打开解决方案时报 :与此流程相关的流程操作未激活 解决方法 :ribbon 导航--系统定置--流程中心--流程--CustomiseRibbon -- ...
- 释放linux的buff/cache
有个linux的服务器,2G内存的,今天登上去一看,内存竟然被占得满满的. ssh上去执行了free. free -m total used free shared buff/cache availa ...
- GIT命令行笔记
一次常规的初始化+推送: git initgit config user.email "you@example.com"git config user.name "asm ...