ScheduledExecutorService定时周期运行指定的任务
一:简单说明
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 {
- @Override
- public 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>
ScheduledExecutorService定时周期运行指定的任务的更多相关文章
- ScheduledExecutorService定时周期执行指定的任务
示例代码 package com.effective.common.concurrent.execute; import java.text.DateFormat; import java.text. ...
- pytest之收集用例规则与运行指定用例
前言 上篇文章相信大家已经了解了pytest在cmd下结合各种命令行参数如何运行测试用例,并输出我们想要看到的信息.那么今天会讲解一下pytest是如何收集我们写好的用例?我们又有哪些方式来运行单个用 ...
- Celery 异步定时周期任务
1/什么是Celery Celery 是基于Python实现的模块,用于执行异步定时周期任务的 其结构的组成是由 1.用户任务app 2.管道 broker 用于存储任务 官方推荐 redis rab ...
- pytest 运行指定用例
pytest运行指定用例 随着软件功能的增加,模块越来越多,也意味用例越来越多,为了节约执行时间,快速得到测试报告与结果,在工作中可以通过运行指定用例,达到快速执行用例 例子目录 spec_sub1_ ...
- windows ping 某个网段,不能运行指定的软件
windows ping 某个网段,不能运行指定的软件 :begin @echo OFF color 0a Title Net Test Tool by:HRuinger Mode con cols= ...
- 12、生命周期-@Bean指定初始化和销毁方法
12.生命周期-@Bean指定初始化和销毁方法 Bean的生命周期:创建->初始化->销毁 容器管理bean的生命周期 我们可以自定义初始方法和销毁方法,容器在bean进行到当期那生命周期 ...
- ScheduledThreadPoolExecutor中定时周期任务的实现源码分析
ScheduledThreadPoolExecutor是一个定时任务线程池,相比于ThreadPoolExecutor最大的不同在于其阻塞队列的实现 首先看一下其构造方法: public Schedu ...
- Java 定时循环运行程序
Timer 和 ScheduledExecutorSeruvce 都能执行定时的循环任务,有函数 scheduleAtFixedRate.但是,如果任务运行时间较长,超过了一个周期时长,下一个任务就会 ...
- runas/cpau/lsrunase使用小结(以管理员运行指定程序)
企业环境中,为了安全起见一般都没有赋予域用户或者企业的PC客户端用户管理员权限. 但偶尔会有个别的程序一定需要管理员身份才能执行,如财务某些程序或专业的应用程序.那么如何不赋予用户管理员权限及密码但又 ...
随机推荐
- python everything is object
python面向对象非常彻底,即使过程式的代码风格,python在运作的时候也是面向对象的.everything is object. 差异 在面向对象的理念上,python和非常工程化的面向对象语言 ...
- JS判断浏览器是否支持某一个CSS3属性的方法
var div = document.createElement('div'); console.log(div.style.transition); //如果支持的话, 会输出 "&quo ...
- 谷歌浏览器chrome假死、卡死、经常无反应,火狐firefox闪黑格子的解决办法(显卡/驱动兼容问题)
问题: chrome 升级到高版本,切换标签后点击,滚轮都没反应,假死不动.F12呼出控制台来开发时更让人揪心.(大概chrome 25更高) 原因: 我的电脑是:集显+512M独显,可切换的 ...
- PHPCMS v9 自定义表单添加验证码验证
1. 在 \phpcms\templates\default\formguide\show.html 中添加验证码显示 <input type="text" id=" ...
- nginx 一般配置实例 静态页面
# 使用的用户和组 user www www; # 指定工作衍生进程数(一般等于CPU的总核数或总核数的两倍,例如两个四核CPU,则总核数为8) worker_processes 8; # 指定错误日 ...
- BZOJ 2330 糖果
Description 幼儿园里有N个小朋友,lxhgww老师现在想要给这些小朋友们分配糖果,要求每个小朋友都要分到糖果.但是小朋友们也有嫉妒心,总是会提出一些要求,比如小明不希望小红分到的糖果比他的 ...
- [BZOJ 2821] 作诗(Poetize) 【分块】
题目链接:BZOJ - 2821 题目分析 因为强制在线了,所以无法用莫队..可以使用分块来做. 做法是,将 n 个数分成 n/x 个块,每个块大小为 x .先预处理出 f[i][j] ,表示从第 i ...
- C# IOCP服务器
C# IOCP服务器 @by 群63438968 这是我写的unity 网络斗地主的服务器源码,本来我想只公开部份服务端代码的,但是为了回报大家的热情,以及曾经和现在的好兄弟,我计划慢慢开源! 告诉 ...
- 以Facebook为案例剖析科技公司应有的工具文化
http://www.36kr.com/p/146507.html 编者按:本文由 @王淮Harry哥 撰写,摘自他即将出版的新书.王淮是 Facebook 早期员工,中国藉第二位工程师第一位研发经理 ...
- Rabbit hunt
poj2606:http://poj.org/problem?id=2606 给你n个点,求在一条直线上的点最多有几个.题解:直接暴力,但是要注意,横坐标相等的情况,这是不能求斜力,只能特殊处理. # ...