java 几种常见的定时器
今天闲着没事就总结了一下在java中常用的几种定时器。
主要有3种java.util.Timer, ScheduledExecutorService和quartz
一.Timer
举个简单例子。每隔5秒自动刷新。
- Timer timerFresh = new Timer();
- timerFresh.schedule(new TimerTask() {
- public void run() {
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- setInputValue();//这里写你的方法,就可以了。
- }
- });
- }
- }, 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
这个目前考虑的比较全面用的比较多。
- /*
- * Copyright 2005 OpenSymphony
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy
- * of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- *
- */
- package org.quartz.examples.example4;
- import java.util.Date;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.quartz.JobDetail;
- import org.quartz.Scheduler;
- import org.quartz.SchedulerFactory;
- import org.quartz.SchedulerMetaData;
- import org.quartz.SimpleTrigger;
- import org.quartz.TriggerUtils;
- import org.quartz.impl.StdSchedulerFactory;
- /**
- * This Example will demonstrate how job parameters can be
- * passed into jobs and how state can be maintained
- *
- * @author Bill Kratzer
- */
- public class JobStateExample {
- public void run() throws Exception {
- Log log = LogFactory.getLog(JobStateExample.class);
- log.info("------- Initializing -------------------");
- // First we must get a reference to a scheduler
- SchedulerFactory sf = new StdSchedulerFactory();
- Scheduler sched = sf.getScheduler();
- log.info("------- Initialization Complete --------");
- log.info("------- Scheduling Jobs ----------------");
- // get a "nice round" time a few seconds in the future....
- long ts = TriggerUtils.getNextGivenSecondDate(null, 10).getTime();
- // job1 will only run 5 times, every 10 seconds
- JobDetail job1 = new JobDetail("job1", "group1", ColorJob.class);
- SimpleTrigger trigger1 = new SimpleTrigger("trigger1", "group1", "job1", "group1",
- new Date(ts), null, 4, 10000);
- // pass initialization parameters into the job
- job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
- job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
- // schedule the job to run
- Date scheduleTime1 = sched.scheduleJob(job1, trigger1);
- log.info(job1.getFullName() +
- " will run at: " + scheduleTime1 +
- " and repeat: " + trigger1.getRepeatCount() +
- " times, every " + trigger1.getRepeatInterval() / 1000 + " seconds");
- // job2 will also run 5 times, every 10 seconds
- JobDetail job2 = new JobDetail("job2", "group1", ColorJob.class);
- SimpleTrigger trigger2 = new SimpleTrigger("trigger2", "group1", "job2", "group1",
- new Date(ts + 1000), null, 4, 10000);
- // pass initialization parameters into the job
- // this job has a different favorite color!
- job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");
- job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
- // schedule the job to run
- Date scheduleTime2 = sched.scheduleJob(job2, trigger2);
- log.info(job2.getFullName() +
- " will run at: " + scheduleTime2 +
- " and repeat: " + trigger2.getRepeatCount() +
- " times, every " + trigger2.getRepeatInterval() / 1000 + " seconds");
- log.info("------- Starting Scheduler ----------------");
- // All of the jobs have been added to the scheduler, but none of the jobs
- // will run until the scheduler has been started
- sched.start();
- log.info("------- Started Scheduler -----------------");
- log.info("------- Waiting 60 seconds... -------------");
- try {
- // wait five minutes to show jobs
- Thread.sleep(60L * 1000L);
- // executing...
- } catch (Exception e) {
- }
- log.info("------- Shutting Down ---------------------");
- sched.shutdown(true);
- log.info("------- Shutdown Complete -----------------");
- SchedulerMetaData metaData = sched.getMetaData();
- log.info("Executed " + metaData.numJobsExecuted() + " jobs.");
- }
- public static void main(String[] args) throws Exception {
- JobStateExample example = new JobStateExample();
- example.run();
- }
- }
需要源码的可以去这里下载 http://dl.dbank.com/c0a4wn14yl
java 几种常见的定时器的更多相关文章
- JAVA几种常见的编码格式(转)
简介 编码问题一直困扰着开发人员,尤其在 Java 中更加明显,因为 Java 是跨平台语言,不同平台之间编码之间的切换较多.本文将向你详细介绍 Java 中编码问题出现的根本原因,你将了解到:Jav ...
- Java几种常见的编码方式
几种常见的编码格式 为什么要编码 不知道大家有没有想过一个问题,那就是为什么要编码?我们能不能不编码?要回答这个问题必须要回到计算机是如何表示我们人类能够理解的符号的,这些符号也就是我们人类使用的语言 ...
- java几种常见的排序算法总结
/*************几种常见的排序算法总结***************************/ package paixu; public class PaiXu { final int ...
- Java几种常见的设计模式
--------------------- 本文来自 旭日Follow_24 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xuri24/article/detail ...
- Java几种常见的排序方法
日常操作中常见的排序方法有:冒泡排序.快速排序.选择排序.插入排序.希尔排序,甚至还有基数排序.鸡尾酒排序.桶排序.鸽巢排序.归并排序等. 冒泡排序是一种简单的排序算法.它重复地走访过要排序的数列,一 ...
- Java几种常见的排序算法
一.所谓排序,就是使一串记录,按照其中的某个或某些关键字的大小,递增或递减的排列起来的操作.排序算法,就是如何使得记录按照要求排列的方法.排序算法在很多领域得到相当地重视,尤其是在大量数据的处理方面. ...
- java几种常见加密算法小试
http://www.cnblogs.com/JCSU/articles/2803598.html http://www.open-open.com/lib/view/open139727425732 ...
- Java几种常见的四舍五入的方法
/* * 在上面简单地介绍了银行家舍入法,目前java支持7中舍入法: 1. ROUND_UP:远离零方向舍入.向绝对值最大的方向舍入,只要舍弃位非0即进位. 2. ROUND_DOWN:趋向零方向舍 ...
- C#3种常见的定时器(多线程)
总结以下三种方法,实现c#每隔一段时间执行代码: 方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间: 方法二:使用System.Timers.Timer类: 方法三:使用Sys ...
随机推荐
- python基础:自定义函数
一.背景 在学习函数之前,一直遵循:面向过程编程,即:根据业务逻辑从上到下实现功能,其往往用一长段代码来实现指定功能,开发过程中最常见的操作就是粘贴复制,也就是将之前实现的代码块复制到现需功能处,如下 ...
- easyUi学习备忘
1.获取datagrid的自身相关的属性方式: jQuery("#grid").datagrid("options").height jQuery(" ...
- Java中的哈希
Java中的哈希 前言 在开发中经常用到HashMap.HashSet等与哈希有关的数据结构,一直只知道这些哈希的数据结构不保证顺序,不清楚具体什么情况.所以在这里大致总结一下. Java的Has ...
- Java中浮点数能连续精确表示整数的范围
转自http://blog.csdn.net/seizef/article/details/5571783#ref_1,有删改. 先简单介绍一下浮点数在计算机中的组成,在Java中采用的浮点数表示法是 ...
- 字符串转成int数组
package lianxi; import java.awt.image.ConvolveOp; public class ZhengshuShuzu { public static void ma ...
- monkey 测试 adb shell monkey
adb shell monkey -p com.android.recorder --throttle 360 --ignore-crashes --monitor-native-crashes -- ...
- 用CSS实现Firefox 和IE 都支持的Alpha透明效果
有的时候,为了实现一些特殊效果,需要将页面元素变透明,本文介绍的就是用 CSS 实现 Firefox 和 IE 都支持的 Alpha 透明效果.CSS: filter:alpha(opacity=50 ...
- Ubuntu16.04.1 安装Redis-Cluster
Redis在3.0版正式引入了集群这个特性.Redis集群是一个分布式(distributed).容错(fault-tolerant)的 Redis内存K/V服务, 集群可以使用的功能是普通单机 Re ...
- CentOS 7 终端设置屏幕分辨率
在grub中我们修改的是/boot/grub/grub.conf,而在grub2中要修改的文件是/boot/grub2/grub.cfg inux16 /vmlinuz-3.10.0-123.el7. ...
- 禁用cookie后
服务器为某个访问者创建一个内存区域,这个就是所谓的session,这个区域的存在是有时间限制的,比如30分钟,这块区域诞生的时候,服务器会给这个区域分配一个钥匙,只有使用这个钥匙才能访问这个区域,这个 ...