java定时器详解(附详细代码)
- 格式:docx
- 大小:25.96 KB
- 文档页数:4
java 定时器用法全文共四篇示例,供读者参考第一篇示例:Java中的定时器是一种功能强大的工具,可以帮助我们实现定时执行任务的功能,例如定时发送邮件、定时备份数据等。
在本文中,我们将详细介绍Java定时器的用法,包括如何使用Java提供的Timer 类、ScheduledExecutorService接口等来创建定时器。
一、使用Timer类创建定时器Java提供了Timer类来实现定时器的功能。
Timer类可以在指定时间间隔内执行指定的任务。
下面是一个使用Timer类创建定时器的简单示例:```javaimport java.util.Timer;import java.util.TimerTask;在上面的示例中,我们首先创建了一个Timer实例,然后创建了一个TimerTask对象,并实现了其中的run方法,该方法中编写了定时执行的任务。
最后调用Timer的schedule方法来设置定时任务的执行时间和间隔。
二、使用ScheduledExecutorService接口创建定时器除了Timer类外,Java还提供了ScheduledExecutorService接口来创建定时器。
ScheduledExecutorService是ExecutorService的子接口,支持延迟执行、周期性执行等功能。
下面是一个使用ScheduledExecutorService接口创建定时器的示例:```javaimport java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;三、定时器的取消和异常处理在实际开发中,我们可能需要在一定条件下取消定时器的执行,或者处理定时任务中可能出现的异常。
下面是一个示例,演示了如何取消定时器的执行,并如何处理任务中可能出现的异常:在上面的示例中,我们在任务的run方法中使用try-catch语句来捕获可能出现的异常,并在另一个任务中取消了定时器的执行。
java中定时器timer类的实现和源代码java中定时器timer类的实现和源代码在Windows编程中可以调用SetTimer在指定窗口安装定时器(Timer),定时器可以在指定的时间间隔周期性回调用户指定的方法,用来执行周期性的任务,如果想取消定时器,可以调用KillTimer取消。
但是在java标准包里中并没有这种类。
下面介绍的这个类包可以实现上述功能。
下面是接口,需要支持定时器功能的类要实现这个接口:TimerClient.javapackage com.ly.util;/*** TimerClient Interface** @version 1.0, 8 October 1995**/public interface TimerClient{void timerEvent(int id);}下面是定时器的实现,包括三个类:TimerCtl,TimerTask,TimerTasks。
其中TimerTask用来描述定时器信息。
TimerTasks是一个TimerTask的列表,这样我们就可以同时在一个应用中安插多个定时器。
TimerCtl是定时器控制类,是个线程,不停地检查TimerTasks中是否有TimerTask到期,要是有TimerTask到达指定的时间,则回调TimerTask指定的 TimerClient的timerEvent接口。
TimerCtl.javapackage com.ly.util;import java.util.Vector;import java.util.Enumeration;//import com.borland.jb.util.Diagnostic;/*** Timer Component** Note:* - The successful operation of this timer requires clients to execute simple, short* code snippets when called back by the engine. Otherwise the queue's delivery* mechanism will be held up** Further work:* - When Thread.Interrupt is implemented we can switch from the busy wait model to* the calculated wait model. Without the interrupt the thread waits for the* calculated interval before waking up. This is a problem if another shorter* request arrives. For now we'll assume the minimum resolution of the timer is* 100ms.** @version 1.0, 2 October 1995**/public class TimerCtl{static TimerTasks timerTasks;public TimerCtl() {}/** Start a timer running*/public static void startTimer(TimerClient client, int eventId, long delay, boolean repeat) {// create the timer if necessaryif (timerTasks == null) {timerTasks = new TimerTasks();timerTasks.start();}//Diagnostic.out.println("TIMER: startTimer"+eventId);// add the new task to the queuetimerTasks.add(client, eventId, delay, repeat);}/** Stop a timer*/public static void stopTimer(TimerClient client, int eventId) {//Diagnostic.out.println("TIMER: stopTimer"+eventId);if(timerTasks != null)timerTasks.end(client, eventId);}}class TimerTasks extends Thread{Vector tasks = new Vector();boolean suspended = false;boolean sleeping = false;/*** Thread task runner*/public void run() {// Loop foreverwhile (true) {long sleepTime = 0;// Ensure that the tasks class is protectedsynchronized (tasks) {//Diagnostic.out.println("TIMER: Tick");// Scan the job list for any jobs which may fire.// Mark one-shot jobs for deletion// Calculate the maximum time we can sleep forsleepTime = scan();// Delete DeletePending jobs. DeletePending jobs result from one-shots which have// been sent, and repeat jobs which have beencancelled. Jobs may have been// cancelled during the Scan process.purge();}// Suspend timer if necessaryif (tasks.size() == 0) {//Diagnostic.out.println("TIMER: Suspend");try {synchronized(this) {suspended = true;wait();}}catch (InterruptedException e) {}}else {//Diagnostic.out.println("TIMER: Suggested Sleeping for "+sleepTime);if (sleepTime >= 0) {try {sleeping = true;sleep(sleepTime);sleeping = false;}catch (InterruptedException i) {//Diagnostic.out.println("TIMER: Caught me napping"); }}}}}/*** Add a new task*/public void add(TimerClient client, int eventId, long delay, boolean repeat) {TimerTask t = new TimerTask(client, eventId, delay, repeat);synchronized (tasks) {tasks.addElement((Object)t);}// Want instant response - wake the thread if it's napping// unfortunately the interrupt() method is not working// if (sleeping)// interrupt();if (suspended) {synchronized(this) {notify();//Diagnostic.out.println("TIMER: Resume");suspended = false;}}}/*** Find the job and mark it for deletion*/public void end(TimerClient client, int eventId) {synchronized (tasks) {for (int i = 0; i < tasks.size(); i++) {TimerTask t = (TimerTask)tasks.elementAt(i);//if (!t.deletePending && t.client == client && t.eventId == eventId)if (t.deletePending == false && t.client == client &&t.eventId == eventId) {// JPBS - if we don't reset 'repeat', deletePending will be set againt.repeat = false;t.deletePending = true;break;}}}}/*** Clear out all the dead wood*/void purge() {for (int i = 0; i < tasks.size(); i++) {TimerTask t = (TimerTask)tasks.elementAt(i);if (t.deletePending) {//Diagnostic.out.println("TIMER: purged");tasks.removeElementAt(i);i--;}}}long scan() {// The value added to the current time determines the MAX time until// the next scan// This is 100 now since thread.interrupt() is not implementedlong nextTime = System.currentTimeMillis() + 100;for (int i = 0; i < tasks.size(); i++) {TimerTask t = (TimerTask)tasks.elementAt(i);// if not already deletePending, test (and possibly send the event)// as a result, the job may be flagged for deletion.// May also be a non-repeating job and so require self deletion if (!t.deletePending)t.test();// if the task didn't get deleted - see what it contributes to the timeif (!t.deletePending)nextTime = Math.min(nextTime, t.timeNext);//Diagnostic.out.println("TIMER: Scanning "+t.eventId+" "+(t.deletePending == true ? "DEL" : ""));}return nextTime - System.currentTimeMillis();}}class TimerTask{TimerClient client;int eventId;long timePrev;long timeDelay;long timeNext;boolean repeat;boolean deletePending;public TimerTask(TimerClient client, int eventId, long timeDelay, boolean repeat) {this.client = client;this.eventId = eventId;this.timeDelay = timeDelay;this.repeat = repeat;// schedule the next click - now + delaytimeNext = System.currentTimeMillis() + timeDelay;deletePending = false;//Diagnostic.out.println("TIMER: Adding New Task"); }public void test() {if (System.currentTimeMillis() >= timeNext) {//Diagnostic.out.println("TIMER: fire");// Fire the eventclient.timerEvent(eventId);// Update the next timetimeNext = System.currentTimeMillis() + timeDelay;deletePending = !repeat;}}}下面是一个使用例子TimerTest.javapackage com.ly.util;import java.io.*;import java.util.*;import com.ly.util.*;/*** Title:* Description:* Copyright: Copyright (c) 2001* Company:* @author dozb* @version 1.0*/public class TimerTest implements TimerClient{ public TimerTest(){starttime();}public void timerEvent(int id){System.out.println("timerEvent...");}public void starttime(){TimerCtl.startTimer(this,1,5*1000,true);}public void stoptime(){TimerCtl.stopTimer(this,1);}public static void main(String[] args){new TimerTest();try{Thread.sleep(200000);}catch(Exception e){}}}通过这种方式,可以高效地使用socket通讯,在异步socket版本没有发布以前,不失是一种解决问题的方法。
Java定时器用法详解一、简介Java定时器(Timer)是Java编程语言中用于实现定时任务的一种工具。
它允许开发者在指定的时间间隔内执行特定的代码块,从而实现定时操作。
本文将详细介绍Java定时器的用法,包括创建定时器、设置任务、启动和停止定时器等内容。
二、创建定时器在Java中,要使用定时器,首先需要导入`java.util.Timer`类。
创建定时器的方法如下:import java.util.Timer;public class MyTimer {public static void main(String[] args) {Timer timer = new Timer();}}三、设置任务定时器的核心功能是执行定时任务,因此需要为定时器设置一个任务。
在Java 中,可以通过创建一个继承自`java.util.TimerTask`的类来实现定时任务。
以下是一个简单的示例:import java.util.TimerTask;class MyTask extends TimerTask {@Overridepublic void run() {System.out.println("定时任务执行");}}四、启动定时器创建好定时器和任务后,接下来需要启动定时器。
可以使用`schedule()`方法来设置定时器的任务和执行间隔。
以下是一个完整的示例:import java.util.Timer;import java.util.TimerTask;class MyTask extends TimerTask {@Overridepublic void run() {System.out.println("定时任务执行");}}public class MyTimer {public static void main(String[] args) {Timer timer = new Timer();MyTask task = new MyTask();timer.schedule(task, 0, 1000); // 立即执行,然后每隔1秒执行一次}}五、停止定时器在某些情况下,可能需要停止定时器的执行。
java delayedworkqueue 定时原理Java delayed workqueue是Java中用于实现定时任务的一种机制。
它可以让开发人员轻松地实现延迟执行任务的功能。
在Java delayed workqueue中,任务被放入一个队列中,等待一段特定的时间后执行。
在本文中,我们将讨论Java delayed workqueue的定时原理,并提供一些示例代码帮助您更好地理解这个机制。
1. 创建DelayedWorkQueue要使用Java delayed workqueue,首先需要创建DelayedWorkQueue实例。
创建实例可以使用下面的代码:```DelayedWorkQueue queue = new DelayedWorkQueue();```在此代码中,我们创建了一个DelayedWorkQueue实例,并将其赋值给名为queue的变量。
该变量将被用于构造、添加、删除和执行延迟任务。
2. 创建延迟任务一旦创建了DelayedWorkQueue实例,我们就可以添加延迟任务了。
这可以通过将任务添加到队列中来完成。
例如,下面的代码演示了如何创建一个延迟任务,并将其添加到队列中:```DelayedTask task = new DelayedTask("Task A", 1000);queue.add(task);```在此代码中,我们使用DelayedTask类创建了一个名为“Task A”的延迟任务,并将其延迟1秒钟后执行。
DelayedTask类的代码如下所示:```public class DelayedTask implements Delayed {private String name;private long delayTime;public DelayedTask(String name, long delayTime) { = name;this.delayTime = System.currentTimeMillis() + delayTime;}@Overridepublic long getDelay(TimeUnit unit) {long diff = delayTime - System.currentTimeMillis(); return unit.convert(diff, LISECONDS); }@Overridepublic int compareTo(Delayed o) {if (this.delayTime < ((DelayedTask) o).delayTime) { return -1;}if (this.delayTime > ((DelayedTask) o).delayTime) { return 1;}return 0;}@Overridepublic String toString() {return "DelayedTask{" +"name='" + name + '\'' +", delayTime=" + delayTime +'}';}}```如上所述,DelayedTask类实现了Delayed接口,该接口包含两个方法:getDelay()和compareTo()。
JAVA定时器的三种方法(详细注解)在Java中,有三种主要的定时器方法可以实现任务的定时执行。
这些方法包括Timer类、ScheduledThreadPoolExecutor类和TimerTask类。
下面将详细介绍这三种定时器方法的使用。
1. Timer类:Timer类是Java提供的一个基本的定时器类,可以用于在指定的时间间隔内执行指定的任务。
Timer类提供了schedule(和scheduleAtFixedRate(两个方法,用于按照指定的时间间隔执行任务。
(1)schedule(方法:该方法用于在指定的时间间隔后执行任务。
它的语法如下:public void schedule(TimerTask task, long delay)参数task表示要执行的任务,它是一个实现了TimerTask接口的类的实例。
参数delay表示延迟的时间,以毫秒为单位。
例如,下面的代码使用Timer类的schedule(方法,在延迟2秒后执行一个任务:```public void ruSystem.out.println("任务执行了");}},2000);```当运行上述代码后,程序将会输出"任务执行了"。
(2)scheduleAtFixedRate(方法:该方法用于以固定的时间间隔执行任务。
它的语法如下:public void scheduleAtFixedRate(TimerTask task, long delay, long period)参数task表示要执行的任务,它是一个实现了TimerTask接口的类的实例。
参数delay表示延迟的时间,以毫秒为单位。
参数period表示每次任务执行间隔的时间,也是以毫秒为单位。
例如,下面的代码使用Timer类的scheduleAtFixedRate(方法,延迟2秒后开始执行一个任务,并且每隔1秒执行一次:```public void ruSystem.out.println("任务执行了");}},2000,1000);```当运行上述代码后,程序将会输出"任务执行了",并且每隔1秒输出一次。
java定时器实现方式Java定时器实现方式Java是一种强大且广泛应用的编程语言,可以用于开发各种类型的应用程序。
在许多应用中,时间管理是非常重要的,其中定时器的使用非常常见。
Java提供了多种实现定时器的方式,本文将一步一步地回答关于Java定时器实现方式的问题。
1. 什么是定时器?定时器是一种工具,用于在指定的时间间隔内执行特定的任务。
它可以用于在应用程序中执行周期性的操作,如生成报告、数据备份、数据同步等。
2. Java中实现定时器的方式有哪些?Java提供了多种实现定时器的方式,包括Timer类、ScheduledExecutorService接口、Quartz框架等。
3. Timer类是如何实现定时器的?Timer类是Java提供的用于实现定时器功能的一个工具类。
它提供了一种简单的方式来安排在未来的某个时间点执行任务。
使用Timer类可以指定任务在间隔固定的时间执行,或者在指定的时间点执行。
使用Timer类实现定时器的步骤如下:- 创建一个Timer对象。
- 创建一个TimerTask对象,该对象表示要执行的任务。
- 使用Timer的schedule()方法安排任务在未来的某个时间点执行。
下面是一个使用Timer类实现定时器的示例代码:javaimport java.util.Timer;import java.util.TimerTask;public class MyTimerTask extends TimerTask {public void run() {在此处编写要执行的任务逻辑}}public class Main {public static void main(String[] args) {Timer timer = new Timer();TimerTask task = new MyTimerTask();安排任务在未来的某个时间点执行(如延迟3秒执行)timer.schedule(task, 3000);}}4. ScheduledExecutorService接口是如何实现定时器的?ScheduledExecutorService接口是Java提供的用于实现定时器功能的接口。
java当中的定时器的4种使⽤⽅式对于开发游戏项⽬的同胞来说,Timer 这个东西肯定不会陌⽣,今天对以前⾃⼰经常使⽤的定时进⾏了⼀番⼩⼩的总结!没有写具体实现的原理,只是列举出了其中的四种⽐较常见的使⽤⽅法,相对⽽⾔,所以只要按照其所列举的例⼦仿照即可!import java.util.Calendar;import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class TimeTest {public static void main(String[] args) {timer1();//timer2();//timer3();//timer4();}// 第⼀种⽅法:设定指定任务task在指定时间time执⾏ schedule(TimerTask task, Date time)public static void timer1() {Timer timer = new Timer();timer.schedule(new TimerTask() {public void run() {System.out.println("-------设定要指定任务--------");}}, 2000);// 设定指定的时间time,此处为2000毫秒}// 第⼆种⽅法:设定指定任务task在指定延迟delay后进⾏固定延迟peroid的执⾏// schedule(TimerTask task, long delay, long period)public static void timer2() {Timer timer = new Timer();timer.schedule(new TimerTask() {public void run() {System.out.println("-------设定要指定任务--------");}}, 1000, 5000);}// 第三种⽅法:设定指定任务task在指定延迟delay后进⾏固定频率peroid的执⾏。
javaTimer(定时调⽤、实现固定时间执⾏)最近需要⽤到定时调⽤的功能。
可以通过java的Timer类来进⾏定时调⽤,下⾯是有关Timer的⼀些相关知识。
其实就Timer来讲就是⼀个调度器,⽽TimerTask呢只是⼀个实现了run⽅法的⼀个类,⽽具体的TimerTask需要由你⾃⼰来实现,例如这样: Timer timer = new Timer();timer.schedule(new TimerTask() {public void run() {System.out.println("11232");}}, 200000 , 1000); 这⾥直接实现⼀个TimerTask(当然,你可以实现多个TimerTask,多个TimerTask可以被⼀个Timer会被分配到多个 Timer中被调度,后⾯会说到Timer的实现机制就是说内部的调度机制),然后编写run⽅法,20s后开始执⾏,每秒执⾏⼀次,当然你通过⼀个 timer对象来操作多个timerTask,其实timerTask本⾝没什么意义,只是和timer集合操作的⼀个对象,实现它就必然有对应的run ⽅法,以被调⽤,他甚⾄于根本不需要实现Runnable,因为这样往往混淆视听了,为什么呢?也是本⽂要说的重点。
在说到timer的原理时,我们先看看Timer⾥⾯的⼀些常见⽅法:1、这个⽅法是调度⼀个task,经过delay(ms)后开始进⾏调度,仅仅调度⼀次。
public void schedule(TimerTask task, long delay)2、在指定的时间点time上调度⼀次。
public void schedule(TimerTask task, Date time)3、这个⽅法是调度⼀个task,在delay(ms)后开始调度,每次调度完后,最少等待period(ms)后才开始调度。
public void schedule(TimerTask task, long delay, long period)4、和上⼀个⽅法类似,唯⼀的区别就是传⼊的第⼆个参数为第⼀次调度的时间。
Java实现定时任务的三种⽅法⽬录1、 sleep2、Timer3、ScheduledExecutorService总结是的,不⽤任何框架,⽤我们朴素的 Java 编程语⾔就能实现定时任务。
今天,栈长就介绍 3 种实现⽅法,教你如何使⽤ JDK 实现定时任务!1、 sleep这也是我们最常⽤的 sleep 休眠⼤法,不只是当作休眠⽤,我们还可以利⽤它很轻松的能实现⼀个简单的定时任务。
实现逻辑:新开⼀个线程,添加⼀个 for/ while 死循环,然后在死循环⾥⾯添加⼀个 sleep 休眠逻辑,让程序每隔 N 秒休眠再执⾏⼀次,这样就达到了⼀个简单定时任务的效果。
实现代码如下:private static void sleepTask() {new Thread(() -> {while (true) {System.out.println("hi, 欢迎关注:Java技术栈");try {// 每隔3秒执⾏⼀次Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}}).start();}这种⽅式⽐较傻⽠化了,只能按固定频率运⾏,不能指定具体运⾏的时间。
另外,上⾯的箭头语法,栈长使⽤了 JDK 8 中的 Lambda 表达式,这⾥就不再撰述了,Java 8 系列实战教程我都写了⼀堆了,不清楚的可以关注公众号:Java技术栈,在后台回复 "java" 阅读,我都整理好了。
2、Timer来看下 JDK ⾃带的 java.util.Timer 类:JDK 1.3 就内置了 java.util.Timer 类,可以⽤来调度 java.util.TimerTask 任务。
⼏个重要的⽅法:schedule:开始调度任务,提供了⼏个包装⽅法;cancle:终⽌任务调度,取消当前调度的所有任务,正在运⾏的任务不受影响;purge:从任务队列中移除所有已取消的任务;另外,java.util.TimerTask 就是实现了 Runnable 接⼝,具体任务逻辑则是在 run ⽅法⾥去实现。
这个类最终功能是每天某个时间点(如每晚22点)执行某一功能.首先介绍java定时器(java.util.Timer)有定时执行计划任务的功能,通过设定定时器的间隔时间,会自动在此间隔时间后执行预先安排好的任务(java.util. TimerTask)如: 每隔一个小时执行任务 timer.schedule(TimerTask, 0, 60 * 60 * 1000);schedule方法的第一个参数是需要执行的任务,此类的类型为java.util.TimerTask,第二个参数为执行任务前等待时间,此处0表示不等待,第三个参数为间隔时间,单位为毫秒由于我们希望当Web工程启动时,定时器能自动开始计时,这样在整个Web工程的生命期里,就会定时的执行任务,因此启动定时器的类不能是一般的类,此处用Servlet的监听器类来启动定时器,通过在配置文件里配置此监听器, 让其在工程启动时自动加载运行,存活期为整个Web工程生命期.要运用Servlet侦听器需要实现javax.servlet.ServletContextListener接口,以下是类设计:public class TimerListener implements ServletContextListener { private Timer timer = null;private SampleTask sampleTask;@Overridepublic void contextDestroyed(ServletContextEvent event) { timer.cancel();event.getServletContext().log("定时器销毁");}@Overridepublic void contextInitialized(ServletContextEvent event) { timer = new Timer(true);sampleTask = new SampleTask(event.getServletContext()); event.getServletContext().log("定时器已启动");timer.schedule(sampleTask, 0, 60 * 60 * 1000);event.getServletContext().log ("已经添加任务调度表");}}public class SampleTask extends TimerTask {private ServletContext context;private static boolean isRunning = false;private static boolean flag = true;private static final int C_SCHEDULE_HOUR = 15;public SampleTask(ServletContext context){this.context = context;}@Overridepublic void run() {Calendar cal = Calendar.getInstance();if (!isRunning) {if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY) && flag) {isRunning = true;context.log("开始执行指定任务");//需要执行的代码isRunning = false;flag = false;context.log("指定任务执行结束");}} else {context.log("上一次任务执行还未结束");}if(C_SCHEDULE_HOUR != cal.get(Calendar.HOUR_OF_DAY)){flag = true;}}}要使用此监听器需要在web.xml中配置,如下:<listener><listener-class>包路径.TimerListener</listener-class></listener>这样在web工程启动时,就会自动启动此监听器.JAVA中Timer定时器调度方法java timer中的时间调度方法主要有:schedule(TimerTask task, Date firstTime, long period)Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.但是如果此时的firstTime小于(时间落后于)当前时间,那么task会立即执行,在调试的时候不方便,因为程序一启动就开始执行了,或许还没有到任务的触发点。
在Jotm中看到⼀个很齐全的定时器,贴出来以防备⽤; package org.objectweb.jotm; import java.util.Vector; /** * *对计时器列表中的计时器进⾏倒计时 */ class Clock extends Thread { private TimerManager tmgr; public Clock(TimerManager tmgr) { super("JotmClock"); if (TraceTm.jta.isDebugEnabled()) { TraceTm.jta.debug("Clock constructor"); } this.tmgr = tmgr; } public void run() { tmgr.clock(); } } /** * *Examda提⽰:出去计时器列表中的过期计时器,如倒计时为负数 */ class Batch extends Thread { private TimerManager tmgr; public Batch(TimerManager tmgr) { super("JotmBatch"); if (TraceTm.jta.isDebugEnabled()) { TraceTm.jta.debug("Batch constructor"); } this.tmgr = tmgr; } public void run() { tmgr.batch(); } } /** *含有两个计时器列表,并且含有两个线程,⼀个线程进⾏计时器的倒计时, *⼀个线程移除过期计时器并且执⾏计时器的监听器动作; */ public class TimerManager { // threads managing the service. private static Batch batchThread; private static Clock clockThread; // lists //计时器列表 private Vector timerList = new Vector(); //过期计时器列表 private Vector expiredList = new Vector(); //单例 private static TimerManager unique = null; private static boolean shuttingdown = false; /** * Constructor */ private TimerManager() { // launch threads for timers batchThread = new Batch(this); batchThread.setDaemon(true); clockThread = new Clock(this); clockThread.setDaemon(true); clockThread.start(); } /** * 这个时间管理器是⼀个单例类; */ public static TimerManager getInstance() { if (unique == null) unique = new TimerManager(); return unique; } //停⽌时间管理器中的计时器; public static void stop(boolean force) { if (TraceTm.jta.isDebugEnabled()) { TraceTm.jta.debug("Stop TimerManager"); } TimerManager tmgr = getInstance(); shuttingdown = true; while (clockThread.isAlive() || batchThread.isAlive()) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } if (TraceTm.jta.isDebugEnabled()) { TraceTm.jta.debug("TimerManager has stopped"); } } public static void stop() { stop(true); } /** * cney speed up the clock x1000 when shutting down * update all timers in the list * each timer expired is put in a special list of expired timers * they will be processed then by the Batch Thread. */ public void clock() { //⽆限循环 while (true) { try { //线程休息⼀秒 Thread.sleep(shuttingdown?1:1000); // 1 second or 1ms shen shuttingdown // Thread.currentThread().sleep(shuttingdown?1:1000); // 1 second or 1ms shen shuttingdown synchronized(timerList) { int found = 0; boolean empty = true; for (int i = 0; i < timerList.size(); i++) { TimerEvent t = (TimerEvent) timerList.elementAt(i); //如果没有活动的计时器,那么计时器队列为空; if (!t.isStopped()) { empty = false; } //如果计时器过期 if (t.update() <= 0) { //从计时器队列中移除 timerList.removeElementAt(i--); if (t.valid()) { //该计时器存在计时器监听器的话,把这个计时器加⼊过期计时器 //如果不存在,则废除,哪个队列都不加⼊ found++; //如果持续的话,则继续把该计时器再次加⼊计时器队列中 if (t.ispermanent() && !shuttingdown) { t.restart(); timerList.addElement(t); } } } // Be sure there is no more ref on bean in this local variable. t = null; } if (found > 0) { //唤醒线程; timerList.notify(); } else { if (empty && shuttingdown) { break; } } } } catch (InterruptedException e) { TraceTm.jta.error("Timer interrupted"); } } synchronized(timerList) { // notify batch so that function can return. timerList.notify(); } } /** * process all expired timers */ public void batch() { while (!(shuttingdown && timerList.isEmpty() && expiredList.isEmpty())) { TimerEvent t; synchronized(timerList) { while (expiredList.isEmpty()) { if (shuttingdown) return; try { //计时器计时线程让如果找到到期的计时器,那么就会唤醒执⾏该计时器的线程执⾏监听器动作 timerList.wait(); } catch (Exception e) { TraceTm.jta.error("Exception in Batch: ", e); } } t = (TimerEvent) expiredList.elementAt(0); expiredList.removeElementAt(0); } //执⾏动作; t.process(); } } /** * add a new timer in the list * @param tel Object that will be notified when the timer expire. * @param timeout nb of seconds before the timer expires. * @param arg info passed with the timer * @param permanent true if the timer is permanent. */ public TimerEvent addTimer(TimerEventListener tel, long timeout, Object arg, boolean permanent) { TimerEvent te = new TimerEvent(tel, timeout, arg, permanent); synchronized(timerList) { } return te; } /** * remove a timer from the list. this is not very efficient. * A better way to do this is TimerEvent.unset() * @deprecated */ public void removeTimer(TimerEvent te) { synchronized(timerList) { timerList.removeElement(te); } } }。
如果要执行一些简单的定时器任务,无须做复杂的控制,也无须保存状态,那么可以考虑使用JDK 入门级的定期器Timer 来执行重复任务。
一、原理JDK中,定时器任务的执行需要两个基本的类:java.util.Timer;java.util.TimerTask;要运行一个定时任务,最基本的步骤如下:1、建立一个要执行的任务TimerTask。
2、创建一个Timer实例,通过Timer提供的schedule()方法,将TimerTask加入到定时器Timer中,同时设置执行的规则即可。
当程序执行了Timer初始化代码后,Timer定时任务就会按照设置去执行。
Timer中的schedule()方法是有多种重载格式的,以适应不同的情况。
该方法的格式如下:void schedule(TimerTask task, Date time)安排在指定的时间执行指定的任务。
void schedule(TimerTask task, Date firstTime, long period)安排指定的任务在指定的时间开始进行重复的固定延迟执行。
void schedule(TimerTask task, long delay)安排在指定延迟后执行指定的任务。
void schedule(TimerTask task, long delay, long period)安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
Timer是线程安全的,此类可扩展到大量同时安排的任务(存在数千个都没有问题)。
其所有构造方法都启动计时器线程。
可以调用cancel() 终止此计时器,丢弃所有当前已安排的任务。
purge()从此计时器的任务队列中移除所有已取消的任务。
此类不提供实时保证:它使用Object.wait(long) 方法来安排任务。
TimerTask是一个抽象类,由Timer 安排为一次执行或重复执行的任务。
它有一个抽象方法run()----计时器任务要执行的操作。
JAVA中的定时器1.⾃⼰写while(true)死循环,来判断是否到达执⾏时间条件这种实现定时任务的⽅式,完全是⾃⼰写代码实现,放在第⼀个介绍,是因为它最灵活,完全由⾃⼰控制,但是缺点是,只适合⼩⼯具类的程序,任务单⼀固定的程序。
实现的简单代码块如下:long interval = 100; // 秒String runTime = "12:50";Date startTime = new Date();boolean runFlag = false;int count = 0;while(true){Date nowTime = new Date();if (!StringUtils.isEmpty(runTime)) {String checkTime = DateUtilsExt.getNowTime("HH:mm");if (runTime.equals(checkTime)) {runFlag = true;}} else if (intervalTime > 0) {long now = nowTime.getTime();long start = startTime.getTime();long interval = (now - start)/1000;//第⼀次执⾏if (count == 0) {runFlag = true;//间隔时间执⾏运⾏间隔到了指定秒以后执⾏} else if (intervalTime <= interval){runFlag = true;}}if (runFlag) {// 执⾏定时任务}}2.java⾃带的⼯具类 timer + timerTask这个⽅式是我们本次导数⼯具所⽤的程序。
⽤着挺⽅便,timer ,timerTask 都是java.util中提供的⼯具类,既可以⽤于java web项⽬,也可以⽤于javase项⽬。
java定时任务Timer和TimerTask使⽤详解timer和timertask是jdk⾃带的定时任务实现,⽆需导⼊第三⽅jar包来完成1、指定多久之后执⾏此任务,注意:只会执⾏⼀次public class TimerTest {Timer timer;public TimerTest(int time){timer = new Timer();timer.schedule(new timerTaskTest(),time*1000);//timer.schedule(执⾏的⽅法,延迟多久执⾏(ms))}public static void main(String[] args) {System.out.println("timer begin...");new TimerTest(3);}class timerTaskTest extends TimerTask{@Overridepublic void run() {System.out.println("time's up!!");}}}2、在指定的时间执⾏任务public class TimerTest1 {Timer timer;public TimerTest1(){Date time = getTime();System.out.println("指定时间time="+time);timer = new Timer();timer.schedule(new TimerTaskTest1(),time);//timer.schedule(执⾏的⽅法,要执⾏的时间)}public Date getTime(){//设置执⾏时间Calendar calendar = Calendar.getInstance();calendar.set(Calendar.HOUR,5);calendar.set(Calendar.MINUTE,46);calendar.set(Calendar.SECOND,00);Date time = calendar.getTime();return time;}public static void main(String[] args) {new TimerTest1();}class TimerTaskTest1 extends TimerTask{public void run() {System.out.println("指定时间执⾏线程任务...");}}}3、在延迟指定时间后以指定的间隔时间循环执⾏定时任务public class TimerTest2 {Timer timer;public TimerTest2(){timer = new Timer();timer.schedule(new TimerTaskTest2(),1000,2000);//tiemr.schedule(执⾏的⽅法,延迟时间,多久执⾏⼀次)}class TimerTaskTest2 extends TimerTask{@Overridepublic void run() {System.out.println("本次任务执⾏时间"+new Date());}}public static void main(String[] args) {new TimerTest2();}}到这⾥定时任务实现类已经完成,如果是web项⽬,则需要在web.xml中配置启动<listener><listener-class>com.sxl.ContextListener</listener-class></listener>配置完成即可。
JAVA:定时器的三种⽅法(详细注解)在Java中为我们提供了Timer来实现定时任务,当然现在还有很多定时任务框架,⽐如说Spring、QuartZ、Linux Cron等等,⽽且性能也更加优越。
但是我们想要深⼊的学习就必须先从最简单的开始。
第⼀种:创建⼀个thread,然后让它在while循环⾥⼀直运⾏着,通过sleep⽅法来达到定时任务的效果,代码如下public class Task1 {public static void main(String[] args) {// run in a second// 每⼀秒钟执⾏⼀次final long timeInterval = 1000;Runnable runnable = new Runnable() {public void run() {while (true) {// ------- code for task to run// ------- 要运⾏的任务代码System.out.println("Hello, stranger");// ------- ends heretry {// sleep():同步延迟数据,并且会阻塞线程Thread.sleep(timeInterval);} catch (InterruptedException e) {e.printStackTrace();}}}};//创建定时器Thread thread = new Thread(runnable);//开始执⾏thread.start();}}第⼆种:启动和去取消任务时可以控制,可以指定你想要的delay(开始执⾏的等待时间)时间,在实现时,Timer类可以调度任务,TimerTask 则是通过在run()⽅法⾥实现具体任务。
Timer实例可以调度多任务,它是线程安全的。
当Timer的构造器被调⽤时,它创建了⼀个线程,这个线程可以⽤来调度任务。
java类Timer和TimerTask的使用这两个类使用起来非常方便,可以完成我们对定时器的绝大多数需求
Timer类是用来执行任务的类,它接受一个TimerTask做参数
Timer有两种执行任务的模式,最常用的是schedule,它可以以两种方式执行任务:1:在某个时间(Data),2:在某个固定的时间之后(int delay).这两种方式都可以指定任务执行的频率.看个简单的例子:
import java.io.IOException;
import java.util.Timer;
public class TimerTest {
public static void main(String[] args){
Timer timer = new Timer();
timer.schedule(new MyTask(), 1000, 2000);//在1秒后执行此任务,每次间隔2秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
while(true){//这个是用来停止此任务的,否则就一直循环执行此任务了
try {
int ch = System.in.read();
if(ch-'c'==0){
timer.cancel();//使用这个方法退出任务
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class MyTask extends java.util.TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("________");
}
}
}
如果你使用的是JDK 5+,还有一个scheduleAtFixedRate模式可以用,在这个模式下,Timer会尽量的让任务在一个固定的频率下运行,举例说明:在上面的例子中,我们想让MyTask在1秒钟后,每两秒钟执行一次,但是因为java不是实时的(其实java实时性很差.....),所以,我们在上个程序中表达的原义并不能够严格执行.如果我们调用的是scheduleAtFixedRate,那么,Timer会尽量让你的Task执行的频率保持在2秒一次.运行上面的程序,假设使用的是scheduleAtFixedRate,那么下面的场景就是可能的:1秒钟后,MyTask 执行一次,因为系统繁忙,之后的2.5秒后MyTask 才得以执行第二次,然后,Timer记下了这个延迟,并尝试在下一个任务的时候弥补这个延迟,那么,1.5秒
后,MyTask 将执行的三次."以固定的频率而不是固定的延迟时间去执行一个任务"
果然很方便吧^_^
下面给出一个复杂点的例子,其中告诉大家怎么退出单个TimerTask,怎么退出
所有Task
package MyTimerTest;
import java.io.IOException;
import java.util.Timer;
/*
* 本类给出了使用Timer和TimerTaske的主要方法,其中包括定制任务,添加任务
* 退出任务,退出定时器.
* 因为TimerTask的status域是包级可访问的,所以没有办法在java.util.包外
* 得到其状态,这对编程造成一些不便 .我们不能判断某个Task的状态了. *
*/
public class TimerTest {
public static void main(String[] args) {
Timer timer = new Timer();
MyTask myTask1 = new MyTask();
MyTask myTask2 = new MyTask();
myTask2.setInfo("myTask-2");
timer.schedule(myTask1, 1000, 2000);
timer.scheduleAtFixedRate(myTask2, 2000, 3000);
while (true) {
try {
byte[] info = new byte[1024];
int len = System.in.read(info);
String strInfo = new String(info, 0, len, "GBK");//从控制台读出信息
if (strInfo.charAt(strInfo.length() - 1) == ' ') { strInfo = strInfo.substring(0, strInfo.length() - 2);
}
if (strInfo.startsWith("Cancel-1")) {
myTask1.cancel();//退出单个任务
// 其实应该在这里判断myTask2是否也退出了,是的话就应该break.但是因为无法在包外得到
// myTask2的状态,所以,这里不能做出是否退出循环的判断.
} else if (strInfo.startsWith("Cancel-2")) {
myTask2.cancel();
} else if (strInfo.startsWith("Cancel-All")) {
timer.cancel();//退出Timer
break;
} else {
// 只对myTask1作出判断,偷个懒^_^
myTask1.setInfo(strInfo);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class MyTask extends java.util.TimerTask {
String info = "^_^";
@Override
public void run() {
// TODO Auto-generated method stub System.out.println(info);
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
= info;
}
}
}。