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

<think>好的,用户想了解Java程序中的定时器。我得先理清楚Java定时器的相关知识,然后一步步解释清楚。 首先,用户可能是个刚开始学Java的开发者,或者需要实现定时任务的功能。需要明确Java中有哪几种定时器,各自的用法和区别。 记得Java原生的定时器工具主要是java.util.Timer和TimerTask,不过可能已经不太推荐使用了,特别是在较新的Java版本中。另外,还有ScheduledExecutorService,这是并发包里的,应该更现代和灵活。还有Spring框架中的@Scheduled注解,可能用户的项目如果用了Spring的话会更方便。 要分点说明,结构清晰。先介绍基本用法,再讲高级功能,然后注意事项。比如Timer和TimerTask的示例代码,如何创建任务,设置延迟和周期。但要注意Timer是单线程的,任务执行时间长会影响后续任务,异常处理的问题。所以推荐使用ScheduledExecutorService,支持多线程,更可靠。 然后提到Spring的@Scheduled,如果用户使用Spring Boot的话,可能更简单,只需要注解和启用调度。不过这可能属于框架部分,需要视情况说明。 还要注意Java 5之后推荐用ScheduledExecutorService替代Timer,这点很重要,避免用户使用过时的技术。 可能需要比较几种方式的优缺点,帮助用户选择合适的方法。比如Timer简单但功能有限,ScheduledExecutorService更强大,Spring的注解方式适合集成在框架中。 最后,提醒定时任务的使用场景,比如定时数据备份、状态检查等,以及在分布式环境下可能需要更复杂的解决方案,比如Quartz或者分布式任务调度框架。 总结的时候要简明扼要,确保用户理解不同方法的适用场景和选择依据。</think>在 Java 程序中,定时器是用于在指定延迟后或按固定间隔周期执行任务的重要工具。以下是逐步说明: 一、基础定时器实现 1. `java.util.Timer` 类 - 创建单线程任务调度器 - 示例代码: ```java Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("任务执行:" + new Date()); } }, 1000, 2000); // 延迟1秒后首次执行,之后每2秒执行 ``` 2. `TimerTask` 抽象类 - 继承实现自定义任务 - 必须重写 run 方法 二、更现代的解决方案 1. `ScheduledExecutorService`(推荐) - Java 5+ 引入的线程池方案 - 示例代码: ```java ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); executor.scheduleAtFixedRate( () -> System.out.println("周期性任务"), 1, // 初始延迟 3, // 周期 TimeUnit.SECONDS ); ``` 三、Spring 框架集成 1. `@Scheduled` 注解 - 需配合 `@EnableScheduling` - 支持 cron 表达式: ```java @Scheduled(cron = "0 0/5 * * * ?") // 每5分钟执行 public void scheduledTask() { // 业务逻辑 } ``` 四、核心特性对比 $$ \begin{array}{|l|c|c|c|} \hline \text{特性} & \text{Timer} & \text{ScheduledExecutor} & \text{@Scheduled} \\ \hline 线程模型 & 单线程 & 线程池 & 线程池 \\ 异常处理 & 终止任务链 & 隔离异常 & 需要自行处理 \\ 时间精度 & 毫秒级 & 纳秒级 & 毫秒级 \\ 分布式支持 & 否 & 否 & 需结合中间件 \\ \hline \end{array} $$ 五、使用建议 1. 简单场景:使用 `ScheduledExecutorService` 2. Spring 项目:优先采用 `@Scheduled` 3. 分布式环境:考虑 Quartz 或 Elastic Job 4. 注意事项: - 避免长时间阻塞任务 - 注意异常处理机制 - 考虑系统时钟变化影响 六、典型应用场景 - 数据缓存刷新 - 定时报表生成 - 心跳检测 - 批量数据处理 建议根据具体需求选择方案,对于新项目推荐直接使用 `ScheduledExecutorService` 或 Spring 的定时任务框架。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值