JAVA timer.schedule用法
来源:互联网 发布:淘宝店铺地址怎么改 编辑:程序博客网 时间:2024/05/16 17:38
timer.schedule(new MyTask(),long time1,long timer2);
今天算是彻底的搞懂了这个曾经让我为之头疼的方法。下面我就重点介绍一下:
第一个参数,是 TimerTask 类,在包:import java.util.TimerTask .使用者要继承该类,并实现public void run() 方法,因为 TimerTask 类 实现了 Runnable 接口。
第二个参数的意思是,当你调用该方法后,该方法必然会调用 TimerTask 类 TimerTask 类 中的 run()方法,这个参数就是这两者之间的差值,转换成汉语的意思就是说,用户调用 schedule() 方法后,要等待这么长的时间才可以第一次执行run() 方法。
第三个参数的意思就是,第一次调用之后,从第二次开始每隔多长的时间调用一次 run() 方法。
[附:]
技术人员在实现内部办公系统与外部网站一体化的时候,最重要的步骤就是从OA系统读取数据,并且根据网站模板生成最终的静态页面。这里就需要一个定时任务,循环的执行。
技术人员在写定时任务的时候,想当然的以为Timer.schedule(TimerTask task, longdelay)就是重复的执行task。程序运行后发现只运行了一次,总觉得是task里的代码有问题,花了很长时间调试代码都没有结果。
仔细研读java api,发现:
schedule(TimerTask task, long delay)的注释:Schedules thespecified task for execution after the specifieddelay。大意是在延时delay毫秒后执行task。并没有提到重复执行
schedule(TimerTask task, long delay, long period)的注释:Schedulesthe specified task for repeated fixed-delay execution, beginningafter the specified delay。大意是在延时delay毫秒后重复的执行task,周期是period毫秒。
这样问题就很明确schedule(TimerTask task, longdelay)只执行一次,schedule(TimerTask task, long delay, longperiod)才是重复的执行。关键的问题在于程序员误以为schedule就是重复的执行,而没有仔细的研究API,一方面也是英文能力不够,浏览API的过程中不能很快的理解到含义。
1.概览
Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。
TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。
简单的一个例程:
- import java.util.Timer;
- import java.util.TimerTask;
- /** *//**
- * Simple demo that uses java.util.Timer to schedule a task to execute
- * once 5 seconds have passed.
- */
- public class Reminder ...{
- Timer timer;
- public Reminder(int seconds) ...{
- timer = new Timer();
- timer.schedule(new RemindTask(), seconds*1000);
- }
- class RemindTask extends TimerTask ...{
- public void run() ...{
- System.out.println("Time''s up!");
- timer.cancel(); //Terminate the timer thread
- }
- }
- public static void main(String args[]) ...{
- System.out.println("About to schedule task.");
- new Reminder(5);
- System.out.println("Task scheduled.");
- }
- }
运行这个小例子,你会首先看到:
About to schedule task.
5秒钟之后你会看到:
Time''s up!
这个小例子可以说明一些用Timer线程实现和计划执行一个任务的基础步骤:
实现自定义的TimerTask的子类,run方法包含要执行的任务代码,在这个例子里,这个子类就是RemindTask。
实例化Timer类,创建计时器后台线程。
实例化任务对象 (new RemindTask()).
制定执行计划。这里用schedule方法,第一个参数是TimerTask对象,第二个参数表示开始执行前的延时时间(单位是milliseconds,这里定义了5000)。还有一种方法可以指定任务的执行时间,如下例,指定任务在晚上23点25分执行:
- //Get the Date corresponding to 11:01:00 pm today.
- Calendar calendar = Calendar.getInstance();
- calendar.set(Calendar.HOUR_OF_DAY, 23);
- calendar.set(Calendar.MINUTE, 25);
- calendar.set(Calendar.SECOND, 0);
- Date time = calendar.getTime();
- timer = new Timer();
- timer.schedule(new RemindTask(), time);
2.终止Timer线程
默认情况下,只要一个程序的timer线程在运行,那么这个程序就会保持运行。当然,你可以通过以下四种方法终止一个timer线程:
调用timer的cancle方法。你可以从程序的任何地方调用此方法,甚至在一个timer task的run方法里。
让timer线程成为一个daemon线程(可以在创建timer时使用new Timer(true)达到这个目地),这样当程序只有daemon线程的时候,它就会自动终止运行。
当timer相关的所有task执行完毕以后,删除所有此timer对象的引用(置成null),这样timer线程也会终止。
调用System.exit方法,使整个程序(所有线程)终止。
Reminder 的例子使用了第一种方式。在这里不能使用第二种方式,因为这里需要程序保持运行直到timer的任务执行完成,如果设成daemon,那么当main线程 结束的时候,程序只剩下timer这个daemon线程,于是程序不会等timer线程执行task就终止了。
有些时候,程序的终止与否 并不只与timer线程有关。举个例子,如果我们使用AWT来beep,那么AWT会自动创建一个非daemon线程来保持程序的运行。下面的代码我们对 Reminder做了修改,加入了beeping功能,于是我们需要加入System.exit的调用来终止程序。
- import java.util.Timer;
- import java.util.TimerTask;
- import java.awt.Toolkit;
- /** *//**
- * Simple demo that uses java.util.Timer to schedule a task to execute
- * once 5 seconds have passed.
- */
- public class ReminderBeep ...{
- Toolkit toolkit;
- Timer timer;
- public ReminderBeep(int seconds) ...{
- toolkit = Toolkit.getDefaultToolkit();
- timer = new Timer();
- timer.schedule(new RemindTask(), seconds*1000);
- }
- class RemindTask extends TimerTask ...{
- public void run() ...{
- System.out.println("Time''s up!");
- toolkit.beep();
- //timer.cancel(); //Not necessary because we call System.exit
- System.exit(0); //Stops the AWT thread (and everything else)
- }
- }
- public static void main(String args[]) ...{
- System.out.println("About to schedule task.");
- new ReminderBeep(5);
- System.out.println("Task scheduled.");
- }
- }
3.反复执行一个任务
先看一个例子:
- public class AnnoyingBeep ...{
- Toolkit toolkit;
- Timer timer;
- public AnnoyingBeep() ...{
- toolkit = Toolkit.getDefaultToolkit();
- timer = new Timer();
- timer.schedule(new RemindTask(),
- 0, //initial delay
- 1*1000); //subsequent rate
- }
- class RemindTask extends TimerTask ...{
- int numWarningBeeps = 3;
- public void run() ...{
- if (numWarningBeeps > 0) ...{
- toolkit.beep();
- System.out.println("Beep!");
- numWarningBeeps--;
- } else ...{
- toolkit.beep();
- System.out.println("Time''s up!");
- //timer.cancel(); //Not necessary because we call System.exit
- System.exit(0); //Stops the AWT thread (and everything else)
- }
- }
- }
- ...
- }
执行,你会看到如下输出:
Task scheduled.
Beep!
Beep! //one second after the first beep
Beep! //one second after the second beep
Time''s up! //one second after the third beep
这里使用了三个参数的schedule方法用来指定task每隔一秒执行一次。如下所列为所有Timer类用来制定计划反复执行task的方法 :
schedule(TimerTask task, long delay, long period)
schedule(TimerTask task, Date time, long period)
scheduleAtFixedRate(TimerTask task, long delay, long period)
scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
当 计划反复执行的任务时,如果你注重任务执行的平滑度,那么请使用schedule方法,如果你在乎的是任务的执行频度那么使用 scheduleAtFixedRate方法。 例如,这里使用了schedule方法,这就意味着所有beep之间的时间间隔至少为1秒,也就是说,如 果有一个beap因为某种原因迟到了(未按计划执行),那么余下的所有beep都要延时执行。如果我们想让这个程序正好在3秒以后终止,无论哪一个 beep因为什么原因被延时,那么我们需要使用scheduleAtFixedRate方法,这样当第一个beep迟到时,那么后面的beep就会以最快 的速度紧密执行(最大限度的压缩间隔时间)。
4.进一步分析schedule和scheduleAtFixedRate
(1) 2个参数的schedule在制定任务计划时, 如果指定的计划执行时间scheduledExecutionTime<= systemCurrentTime,则task会被立即执行。scheduledExecutionTime不会因为某一个task的过度执行而改变。
(2) 3个参数的schedule在制定反复执行一个task的计划时,每一次执行这个task的计划执行时间随着前一次的实际执行时间而变,也就是 scheduledExecutionTime(第n+1次)=realExecutionTime(第n次)+periodTime。也就是说如果第n 次执行task时,由于某种原因这次执行时间过长,执行完后的systemCurrentTime>= scheduledExecutionTime(第n+1次),则此时不做时隔等待,立即执行第n+1次task,而接下来的第n+2次task的 scheduledExecutionTime(第n+2次)就随着变成了realExecutionTime(第n+1次)+periodTime。说 白了,这个方法更注重保持间隔时间的稳定。
(3)3个参数的scheduleAtFixedRate在制定反复执行一个task的计划时,每一次 执行这个task的计划执行时间在最初就被定下来了,也就是scheduledExecutionTime(第n次)=firstExecuteTime +n*periodTime;如果第n次执行task时,由于某种原因这次执行时间过长,执行完后的systemCurrentTime>= scheduledExecutionTime(第n+1次),则此时不做period间隔等待,立即执行第n+1次task,而接下来的第n+2次的 task的scheduledExecutionTime(第n+2次)依然还是firstExecuteTime+(n+2)*periodTime这 在第一次执行task就定下来了。说白了,这个方法更注重保持执行频率的稳定。
5.一些注意的问题
每一个Timer仅对应唯一一个线程。
Timer不保证任务执行的十分精确。
Timer类的线程安全的。
- JAVA timer.schedule用法
- timer.schedule定时器用法
- timer.schedule定时器用法
- java.util.Timer.schedule和scheduleAtFixedRate的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- Timer中schedule的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- Timer中schedule()的用法
- timer.schedule —— timer定时器的用法
- timer.schedule —— timer定时器的用法
- 《JAVA与模式》之装饰模式
- Android Support v4、v7、v13的区别和应用场景
- Android获取Manifest中<meta-data>元素的值
- Activity间用Intent和Bundle传递参数
- java程序设计基础_陈国君版第五版_第四章例题
- JAVA timer.schedule用法
- 常量指针和指针常量的区别详解
- (java)Subsets II
- AsyncTask的实现
- java反射之获取Class对象
- lightOJ 1186 Incredible Chess
- Masonry简单使用
- 利用Nginx 代理输出缩放图片
- SharedPreferences详解