一:简单说明

ScheduleExecutorService接口中有四个重要的方法,当中scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比較方便。

以下是该接口的原型定义

java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executor

接口scheduleAtFixedRate原型定义及參数说明

[java] view
plain
copy

  1. public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
  2. long initialDelay,
  3. long period,
  4. TimeUnit unit);

command:运行线程

initialDelay:初始化延时

period:两次開始运行最小间隔时间

unit:计时单位

接口scheduleWithFixedDelay原型定义及參数说明

[java] view
plain
copy

  1. public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
  2. long initialDelay,
  3. long delay,
  4. TimeUnit unit);

command:运行线程

initialDelay:初始化延时

period:前一次运行结束到下一次运行開始的间隔时间(间隔运行延迟时间)

unit:计时单位

二:功能演示样例

1.按指定频率周期运行某个任务。

初始化延迟0ms開始运行,每隔100ms又一次运行一次任务。

[java] view
plain
copy

  1. /**
  2. * 以固定周期频率运行任务
  3. */
  4. public static void executeFixedRate() {
  5. ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  6. executor.scheduleAtFixedRate(
  7. new EchoServer(),
  8. 0,
  9. 100,
  10. TimeUnit.MILLISECONDS);
  11. }

间隔指的是连续两次任务開始运行的间隔。

2.按指定频率间隔运行某个任务。

初始化时延时0ms開始运行,本次运行结束后延迟100ms開始下次运行。

[java] view
plain
copy

  1. /**
  2. * 以固定延迟时间进行运行
  3. * 本次任务运行完毕后,须要延迟设定的延迟时间,才会运行新的任务
  4. */
  5. public static void executeFixedDelay() {
  6. ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  7. executor.scheduleWithFixedDelay(
  8. new EchoServer(),
  9. 0,
  10. 100,
  11. TimeUnit.MILLISECONDS);
  12. }

3.周期定时运行某个任务。

有时候我们希望一个任务被安排在凌晨3点(訪问较少时)周期性的运行一个比較耗费资源的任务,能够使用以下方法设定每天在固定时间运行一次任务。

[java] view
plain
copy

  1. /**
  2. * 每天晚上8点运行一次
  3. * 每天定时安排任务进行运行
  4. */
  5. public static void executeEightAtNightPerDay() {
  6. ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  7. long oneDay = 24 * 60 * 60 * 1000;
  8. long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();
  9. initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
  10. executor.scheduleAtFixedRate(
  11. new EchoServer(),
  12. initDelay,
  13. oneDay,
  14. TimeUnit.MILLISECONDS);
  15. }
[java] view
plain
copy

  1. /**
  2. * 获取指定时间相应的毫秒数
  3. * @param time "HH:mm:ss"
  4. * @return
  5. */
  6. private static long getTimeMillis(String time) {
  7. try {
  8. DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
  9. DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
  10. Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
  11. return curDate.getTime();
  12. } catch (ParseException e) {
  13. e.printStackTrace();
  14. }
  15. return 0;
  16. }

4.辅助代码

[java] view
plain
copy

  1. class EchoServer implements Runnable {
  2. @Override
  3. public void run() {
  4. try {
  5. Thread.sleep(50);
  6. } catch (InterruptedException e) {
  7. e.printStackTrace();
  8. }
  9. System.out.println("This is a echo server. The current time is " +
  10. System.currentTimeMillis() + ".");
  11. }
  12. }

三:一些问题

上面写的内容有不严谨的地方,比方对于scheduleAtFixedRate方法,当我们要运行的任务大于我们指定的运行间隔时会怎么样呢?

对于中文API中的凝视,我们可能会被忽悠,觉得不管怎么样,它都会依照我们指定的间隔进行运行,事实上当运行任务的时间大于我们指定的间隔时间时,它并不会在指定间隔时开辟一个新的线程并发运行这个任务。而是等待该线程运行完成。

源代码凝视例如以下:

[java] view
plain
copy

  1. * Creates and executes a periodic action that becomes enabled first
  2. * after the given initial delay, and subsequently with the given
  3. * period; that is executions will commence after
  4. * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
  5. * <tt>initialDelay + 2 * period</tt>, and so on.
  6. * If any execution of the task
  7. * encounters an exception, subsequent executions are suppressed.
  8. * Otherwise, the task will only terminate via cancellation or
  9. * termination of the executor.  If any execution of this task
  10. * takes longer than its period, then subsequent executions
  11. * may start late, but will not concurrently execute.

依据凝视中的内容,我们须要注意的时,我们须要捕获最上层的异常,防止出现异常中止运行,导致周期性的任务不再运行。

四:除了我们自己实现定时任务之外,我们能够使用Spring帮我们完毕这种事情。

Spring自己主动定时任务配置方法(我们要运行任务的类名为com.study.MyTimedTask)

[html] view
plain
copy

  1. <bean id="myTimedTask" class="com.study.MyTimedTask"/>
[html] view
plain
copy

  1. <bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  2. <property name="targetObject" ref="myTimedTask"/>
  3. <property name="targetMethod" value="execute"/>
  4. <property name="concurrent" value="false"/>
  5. </bean>
[html] view
plain
copy

  1. <bean id="myTimedTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
  2. <property name="jobDetail" ref="doMyTimedTask"/>
  3. <property name="cronExpression" value="0 0 2 * ?"/>
  4. </bean>
[html] view
plain
copy

  1. <bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  2. <property name="triggers">
  3. <list>
  4. <ref local="myTimedTaskTrigger"/>
  5. </list>
  6. </property>
  7. </bean>
[html] view
plain
copy

  1. <bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  2. <property name="triggers">
  3. <list>
  4. <bean class="org.springframework.scheduling.quartz.CronTriggerBean">
  5. <property name="jobDetail"/>
  6. <bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  7. <property name="targetObject">
  8. <bean class="com.study.MyTimedTask"/>
  9. </property>
  10. <property name="targetMethod" value="execute"/>
  11. <property name="concurrent" value="false"/>
  12. </bean>
  13. </property>
  14. <property name="cronExpression" value="0 0 2 * ?"/>
  15. </bean>
  16. </list>
  17. </property>
  18. </bean>

ScheduledExecutorService定时周期运行指定的任务的更多相关文章

  1. ScheduledExecutorService定时周期执行指定的任务

    示例代码 package com.effective.common.concurrent.execute; import java.text.DateFormat; import java.text. ...

  2. pytest之收集用例规则与运行指定用例

    前言 上篇文章相信大家已经了解了pytest在cmd下结合各种命令行参数如何运行测试用例,并输出我们想要看到的信息.那么今天会讲解一下pytest是如何收集我们写好的用例?我们又有哪些方式来运行单个用 ...

  3. Celery 异步定时周期任务

    1/什么是Celery Celery 是基于Python实现的模块,用于执行异步定时周期任务的 其结构的组成是由 1.用户任务app 2.管道 broker 用于存储任务 官方推荐 redis rab ...

  4. pytest 运行指定用例

    pytest运行指定用例 随着软件功能的增加,模块越来越多,也意味用例越来越多,为了节约执行时间,快速得到测试报告与结果,在工作中可以通过运行指定用例,达到快速执行用例 例子目录 spec_sub1_ ...

  5. windows ping 某个网段,不能运行指定的软件

    windows ping 某个网段,不能运行指定的软件 :begin @echo OFF color 0a Title Net Test Tool by:HRuinger Mode con cols= ...

  6. 12、生命周期-@Bean指定初始化和销毁方法

    12.生命周期-@Bean指定初始化和销毁方法 Bean的生命周期:创建->初始化->销毁 容器管理bean的生命周期 我们可以自定义初始方法和销毁方法,容器在bean进行到当期那生命周期 ...

  7. ScheduledThreadPoolExecutor中定时周期任务的实现源码分析

    ScheduledThreadPoolExecutor是一个定时任务线程池,相比于ThreadPoolExecutor最大的不同在于其阻塞队列的实现 首先看一下其构造方法: public Schedu ...

  8. Java 定时循环运行程序

    Timer 和 ScheduledExecutorSeruvce 都能执行定时的循环任务,有函数 scheduleAtFixedRate.但是,如果任务运行时间较长,超过了一个周期时长,下一个任务就会 ...

  9. runas/cpau/lsrunase使用小结(以管理员运行指定程序)

    企业环境中,为了安全起见一般都没有赋予域用户或者企业的PC客户端用户管理员权限. 但偶尔会有个别的程序一定需要管理员身份才能执行,如财务某些程序或专业的应用程序.那么如何不赋予用户管理员权限及密码但又 ...

随机推荐

  1. 本大神教你用PHP把文本内容转换成16进制数字,进行加密

    <?php $a="杨波"; $b = bin2hex($a); echo $a."<br />"; $c = pack("H*&q ...

  2. Node 之 Express 学习笔记 第二篇 Express 4x 骨架详解

    周末,没事就来公司加班继续研究一下Express ,这也许也是单身狗的生活吧. 1.目录结构: bin, 存放启动项目的脚本文件 node_modules, 项目所有依赖的库,以及存放 package ...

  3. wdcp-apache开启KeepAlive提高响应速度

    因为我们的网站,媒体文件,js文件,css文件等都在同一个服务器上,并且,我们网站有非常多的图片,所以当建立好tcp链接之后,不应该马上关闭连接,因为每建立一次连接还要进行dns解析,以及启动一个ht ...

  4. python 图片压缩存储

    python(PIL)图像处理(等比例压缩.裁剪压缩) 缩略(水印)图 http://outofmemory.cn/code-snippet/12264/python-PIL-image-proces ...

  5. Mrakdown文本编辑器

    http://www.csdn.net/article/2014-05-05/2819623 WMD WMD (wmd-editor)是一个简单轻量级的HTML编辑器,使用的是 Markdown 文本 ...

  6. Day8 面向对象(补充)

    私有字段 class Foo: def __init__(self, name): self.__name = name def f1(self): print(self.__name) class ...

  7. 如何在search中动态的显示和隐藏tree中的字段

    在tree定义 invisible 来自context <field name="country_id" invisible="context.get('invis ...

  8. bzoj3047: Freda的传呼机 && 2125: 最短路

    Description 为了随时与rainbow快速交流,Freda制造了两部传呼机.Freda和rainbow所在的地方有N座房屋.M条双向光缆.每条光缆连接两座房屋,传呼机发出的信号只能沿着光缆传 ...

  9. WIN7 IIS ASP网站 打不开的解决办法

    WIN7 IIS ASP网站 打不开,通常是访问ACCESS数据库的报错了但在未对IIS和IE作设置的情况,是不能正确的显示错误的,从而也不能解决问题 为解决这个问题,我在网上找了很久,虽然最终解决了 ...

  10. MySQL ubuntu启动

    service mysql start 启动 service mysql restart 重启 service mysql stop 停止 mysql -uroot -ppassword 登入mysq ...