今天闲着没事就总结了一下在java中常用的几种定时器。

主要有3种java.util.Timer, ScheduledExecutorService和quartz

一.Timer

举个简单例子。每隔5秒自动刷新。

  1. Timer timerFresh = new Timer();
  2. timerFresh.schedule(new TimerTask() {
  3. public void run() {
  4. Display.getDefault().syncExec(new Runnable() {
  5. public void run() {
  6. setInputValue();//这里写你的方法,就可以了。
  7. }
  8. });
  9. }
  10. }, 5000, 5000);

二.ScheduledExecutorService

ScheduledExecutorService
schedule(Runnablecommand, long delay, TimeUnitunit) : ScheduledFuture
schedule(Callable<V> callable, long delay, TimeUnitunit) : ScheduledFuture
scheduleAtFixedRate(Runnablecomand, long initDelay, long period, TimeUnitunit) : ScheduledFuture
scheduleWithFixedDelay(Runnablecommand, long initDelay, long delay, TimeUnitunit) :

ScheduledFuturejava.util.concurrent.Executors是ScheduledExecutorService的工厂类,通过Executors,你可以创建你所需要的ScheduledExecutorService。JDK 1.5之后有了ScheduledExecutorService,不建议你再使用java.util.Timer,因为它无论功能性能都不如ScheduledExecutorService。
ScheduledExecutorService
ScheduledTaskSubmitter
ScheduleFuture<Object> future = scheduler.schedule(task, 1, TimeUnit.SECONDS);
// 等待到任务被执行完毕返回结果
// 如果任务执行出错,这里会抛ExecutionException
future.get();
//取消调度任务
future.cancel();

ScheduledFuturejava.util.concurrent.Executors是ScheduledExecutorService的工厂类,通过Executors,你可以创建你所需要的ScheduledExecutorService。JDK 1.5之后有了ScheduledExecutorService,不建议你再使用java.util.Timer,因为它无论功能性能都不如ScheduledExecutorService。

比如这篇文章讲的很好。

在Timer和ScheduledExecutorService间决择

http://sunnylocus.javaeye.com/blog/530969

三.quartz

这个目前考虑的比较全面用的比较多。

  1. /*
  2. * Copyright 2005 OpenSymphony
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy
  6. * of the License at
  7. *
  8. *   http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations
  14. * under the License.
  15. *
  16. */
  17. package org.quartz.examples.example4;
  18. import java.util.Date;
  19. import org.apache.commons.logging.Log;
  20. import org.apache.commons.logging.LogFactory;
  21. import org.quartz.JobDetail;
  22. import org.quartz.Scheduler;
  23. import org.quartz.SchedulerFactory;
  24. import org.quartz.SchedulerMetaData;
  25. import org.quartz.SimpleTrigger;
  26. import org.quartz.TriggerUtils;
  27. import org.quartz.impl.StdSchedulerFactory;
  28. /**
  29. * This Example will demonstrate how job parameters can be
  30. * passed into jobs and how state can be maintained
  31. *
  32. * @author Bill Kratzer
  33. */
  34. public class JobStateExample {
  35. public void run() throws Exception {
  36. Log log = LogFactory.getLog(JobStateExample.class);
  37. log.info("------- Initializing -------------------");
  38. // First we must get a reference to a scheduler
  39. SchedulerFactory sf = new StdSchedulerFactory();
  40. Scheduler sched = sf.getScheduler();
  41. log.info("------- Initialization Complete --------");
  42. log.info("------- Scheduling Jobs ----------------");
  43. // get a "nice round" time a few seconds in the future....
  44. long ts = TriggerUtils.getNextGivenSecondDate(null, 10).getTime();
  45. // job1 will only run 5 times, every 10 seconds
  46. JobDetail job1 = new JobDetail("job1", "group1", ColorJob.class);
  47. SimpleTrigger trigger1 = new SimpleTrigger("trigger1", "group1", "job1", "group1",
  48. new Date(ts), null, 4, 10000);
  49. // pass initialization parameters into the job
  50. job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
  51. job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
  52. // schedule the job to run
  53. Date scheduleTime1 = sched.scheduleJob(job1, trigger1);
  54. log.info(job1.getFullName() +
  55. " will run at: " + scheduleTime1 +
  56. " and repeat: " + trigger1.getRepeatCount() +
  57. " times, every " + trigger1.getRepeatInterval() / 1000 + " seconds");
  58. // job2 will also run 5 times, every 10 seconds
  59. JobDetail job2 = new JobDetail("job2", "group1", ColorJob.class);
  60. SimpleTrigger trigger2 = new SimpleTrigger("trigger2", "group1", "job2", "group1",
  61. new Date(ts + 1000), null, 4, 10000);
  62. // pass initialization parameters into the job
  63. // this job has a different favorite color!
  64. job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");
  65. job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
  66. // schedule the job to run
  67. Date scheduleTime2 = sched.scheduleJob(job2, trigger2);
  68. log.info(job2.getFullName() +
  69. " will run at: " + scheduleTime2 +
  70. " and repeat: " + trigger2.getRepeatCount() +
  71. " times, every " + trigger2.getRepeatInterval() / 1000 + " seconds");
  72. log.info("------- Starting Scheduler ----------------");
  73. // All of the jobs have been added to the scheduler, but none of the jobs
  74. // will run until the scheduler has been started
  75. sched.start();
  76. log.info("------- Started Scheduler -----------------");
  77. log.info("------- Waiting 60 seconds... -------------");
  78. try {
  79. // wait five minutes to show jobs
  80. Thread.sleep(60L * 1000L);
  81. // executing...
  82. } catch (Exception e) {
  83. }
  84. log.info("------- Shutting Down ---------------------");
  85. sched.shutdown(true);
  86. log.info("------- Shutdown Complete -----------------");
  87. SchedulerMetaData metaData = sched.getMetaData();
  88. log.info("Executed " + metaData.numJobsExecuted() + " jobs.");
  89. }
  90. public static void main(String[] args) throws Exception {
  91. JobStateExample example = new JobStateExample();
  92. example.run();
  93. }
  94. }

需要源码的可以去这里下载 http://dl.dbank.com/c0a4wn14yl

java 几种常见的定时器的更多相关文章

  1. JAVA几种常见的编码格式(转)

    简介 编码问题一直困扰着开发人员,尤其在 Java 中更加明显,因为 Java 是跨平台语言,不同平台之间编码之间的切换较多.本文将向你详细介绍 Java 中编码问题出现的根本原因,你将了解到:Jav ...

  2. Java几种常见的编码方式

    几种常见的编码格式 为什么要编码 不知道大家有没有想过一个问题,那就是为什么要编码?我们能不能不编码?要回答这个问题必须要回到计算机是如何表示我们人类能够理解的符号的,这些符号也就是我们人类使用的语言 ...

  3. java几种常见的排序算法总结

    /*************几种常见的排序算法总结***************************/ package paixu; public class PaiXu { final int  ...

  4. Java几种常见的设计模式

    --------------------- 本文来自 旭日Follow_24 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xuri24/article/detail ...

  5. Java几种常见的排序方法

    日常操作中常见的排序方法有:冒泡排序.快速排序.选择排序.插入排序.希尔排序,甚至还有基数排序.鸡尾酒排序.桶排序.鸽巢排序.归并排序等. 冒泡排序是一种简单的排序算法.它重复地走访过要排序的数列,一 ...

  6. Java几种常见的排序算法

    一.所谓排序,就是使一串记录,按照其中的某个或某些关键字的大小,递增或递减的排列起来的操作.排序算法,就是如何使得记录按照要求排列的方法.排序算法在很多领域得到相当地重视,尤其是在大量数据的处理方面. ...

  7. java几种常见加密算法小试

    http://www.cnblogs.com/JCSU/articles/2803598.html http://www.open-open.com/lib/view/open139727425732 ...

  8. Java几种常见的四舍五入的方法

    /* * 在上面简单地介绍了银行家舍入法,目前java支持7中舍入法: 1. ROUND_UP:远离零方向舍入.向绝对值最大的方向舍入,只要舍弃位非0即进位. 2. ROUND_DOWN:趋向零方向舍 ...

  9. C#3种常见的定时器(多线程)

    总结以下三种方法,实现c#每隔一段时间执行代码: 方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间: 方法二:使用System.Timers.Timer类: 方法三:使用Sys ...

随机推荐

  1. php面向对象的基础:创建OOP的方法

    方法的创建 class Computer{ public function _run(){ return '我是类的一个公共方法'; } } $computer = new Computer(); / ...

  2. GForms开发平台

    1. 开发平台概述 1.1. 产品概述 GForms开发平台让开发人员甚至非技术人员在短短几分钟内创建全功能的展现服务,让开发团队更加适应客户和市场的需求,从而提高客户服务和速度实现收益. GForm ...

  3. 学习笔记:JavaScript传参方式———ECMAScript中所有函数的参数都是按值传递

    我们把命名参数(arguments)视为局部变量,在向参数传递基本类型值时,如同基本类型变量的复制一样,传递一个副本,参数在函数内部的改变不会影响外部的基本类型值.如: function add10( ...

  4. HDU1022 Train Problem I 栈的模拟

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1042 栈的模拟,题目大意是已知元素次序, 判断出栈次序是否合理. 需要考虑到各种情况, 分类处理. 常 ...

  5. Google Maps投影在ArcGIS中的设置

    Google Maps采用的地图投影为Web Mercator,其优点为不同维度其形状保持不变,当然面积要发生变化. ArcGIS9.3中可以直接设置为WGS 1984 Web Mercator,操作 ...

  6. C# 玩家昵称屏蔽敏感字眼

    功能:使用正则  对玩家昵称处理,如果含有 屏蔽字库里的敏感字眼进行屏蔽.已封装成dll 1.屏蔽字库处理成所需要的正则格式:(所需正则表达式格式:".*((XX)|(XX)|(XX)|.. ...

  7. HttpWebResponse取不到Cookie?原来是因为被跳转了

    今天做模拟登陆的时候,发现HttpWebResponse的Cookie都为空,但是Fiddler看是有的...后来看见是302状态,才知道请求这个的时候,Response回来已经是跳转了...这样Co ...

  8. activiti源码分析(一)设计模式

    对activiti有基本了解的朋友都知道,activiti暴露了七个接口来提供工作流的相关服务,这些接口具体是如何实现的呢?查看源码发现其实现的形式大体如下: public class Runtime ...

  9. Nginx,LVS,HAProxy,负载均衡之选择

    Nginx的优点:性能好,可以负载超过1万的并发.功能多,除了负载均衡,还能作Web服务器,而且可以通过Geo模块来实现流量分配.社区活跃,第三方补丁和模块很多支持gzip proxy缺点:不支持se ...

  10. 百度的domain命令到底有用吗?

    曾几何时,站长和seoer们在百度输入domain:xxxxxxxx的时候弹出的结果数量让多少人兴奋和失落,为什么我们对百度的domain命令如此着迷呢?因为我们都认为百度的domain命令是查询网站 ...