java定时器详解(附详细代码)

合集下载

java 定时器用法

java 定时器用法

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类的实现和源代码

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定时器的使用(Scheduler )

java定时器的使用(Scheduler )
for (int i = 0; i < ipLength; i++) {
ip = dataMap.getString("ip" + i);
for (int j = 0; j < tablenameLength; j++) {
scheduler.DEFAULT_GROUP, time);
//将作业和触发器添加到调度器
scheduler.scheduleJob(jobDetail, trigger);
try{
//建立作业调度器
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//判断作业调度内是否有作业,如果有将其删除
if (!scheduler.isShutdown()) {
WebApplicationContext wc=(WebApplicationContext)dataMap.get("wcx");
String ip = "";
String tablename = "";
scheduler.deleteJob("ReceiveOnTimed", Scheduler.DEFAULT_GROUP);
}
//删除调度器的作业后,新建一个我们现在要完成的作业,该作业所需要的类是ReceiveJobd.class,作业名字是ReceiveOnTimes,所属分组是Scheduler.DEFAULT_GROUP
ea.start();
}
}
Scheduler scheduler = (Scheduler) dataMap.get("scheduler");

java 定时器用法

java 定时器用法

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 delayedworkqueue 定时原理

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定时器的三种方法(详细注解)

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是一种强大且广泛应用的编程语言,可以用于开发各种类型的应用程序。

在许多应用中,时间管理是非常重要的,其中定时器的使用非常常见。

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种使用方式

java当中的定时器的4种使用方式

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的执⾏。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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;
}
}
}。

相关文档
最新文档