`

用java.util.Timer定时执行任务

    博客分类:
  • java
 
阅读更多

      如果要在程序中定时执行任务,可以使用java.util.Timer这个类实现。使用Timer类需要一个继承了 java.util.TimerTask的类。TimerTask是一个虚类,需要实现它的run方法,实际上是他implements了 Runnable接口,而把run方法留给子类实现。
      下面是我的一个例子:

class  Worker extends TimerTask  {
  
public   void  run()  {
    System.
out .println( " 我在工作啦! " );
  }

}


      Timer类用schedule方法或者scheduleAtFixedRate方法启动定时执行,schedule重载了四个版本,scheduleAtFixedRate重载了两个。每个方法的实现都不同,下面是每个方法的说明:

schedule

public void schedule
(TimerTask
 task,
                     long delay)
Schedules the specified task for execution after the specified delay.
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, or timer was cancelled.

说明:该方法会在设定的延时后执行一次任务。


schedule

public void schedule
(TimerTask
 task,
                     Date
 time)
Schedules the specified task for execution at the specified time. If the time is in the past, the task is scheduled for immediate execution.
Parameters:
task - task to be scheduled.
time - time at which task is to be executed.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:该方法会在指定的时间点执行一次任务。


schedule

public void schedule
(TimerTask
 task,
                     long delay,
                     long period)
Schedules the specified task for repeated fixed-delay execution , beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-delay execution is appropriate for recurring activities that require "smoothness." In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed in response to human input, such as automatically repeating a character as long as a key is held down.

Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:该方法会在指定的延时后执行任务,并且在设定的周期定时执行任务。


schedule

public void schedule
(TimerTask
 task,
                     Date
 firstTime,
                     long period)
Schedules the specified task for repeated fixed-delay execution , beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-delay execution is appropriate for recurring activities that require "smoothness." In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed in response to human input, such as automatically repeating a character as long as a key is held down.

Parameters:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:该方法会在指定的时间点执行任务,然后从该时间点开始,在设定的周期定时执行任务。特别的,如果设定的时间点在当前时间之前,任务会被马上执行,然后开始按照设定的周期定时执行任务。


scheduleAtFixedRate

public void scheduleAtFixedRate
(TimerTask
 task,
                                long delay,
                                long period)
Schedules the specified task for repeated fixed-rate execution , beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:该方法和schedule的相同参数的版本类似,不同的是,如果该任务因为某些原因(例如垃圾收集)而延迟执行,那么接下来的任务会尽可能的快速执行,以赶上特定的时间点。


scheduleAtFixedRate

public void scheduleAtFixedRate
(TimerTask
 task,
                                Date
 firstTime,
                                long period)
Schedules the specified task for repeated fixed-rate execution , beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:和上一个方法类似。

      下面是我的一个测试片断:

   public   static   void  main(String[] args) throws Exception  {
    Timer timer 
=   new  Timer( false );
    timer.schedule(
new  Worker(),  new  Date(System.currentTimeMillis()  +   1000 ));
  }
分享到:
评论

相关推荐

    java.util.timer实现的简单定时任务

    Java.util.Timer类是Java标准库提供的一种简单但功能有限的定时任务执行机制。它允许开发者在指定的时间间隔或特定时间点执行任务,非常适合处理一次性或周期性的后台操作。本篇文章将深入探讨如何使用Timer和...

    java.util.pdf

    同时,提及了Timer和TimerTask,它们用于任务调度,这是java.util的一部分,用于在后台线程中安排任务执行。另外,还提到了异常类EmptyStackException和NoSuchElementException,它们分别在Stack类和Enumeration接口...

    java.util.concurrent.uml.pdf

    标题中提到了“java.util.concurrent.uml.pdf”,这表明文件是一份Java并发编程工具包java.util.concurrent的UML(统一建模语言)类结构图的PDF格式文件。UML图能够帮助开发者理解Java并发包中的类、接口及其关系,...

    java.util包总结

    13. Timer和TimerTask:定时任务调度,可以安排一次或周期性的任务执行。 14. Bitset:位集,用于高效存储和操作位标志。 15. Iterator和ListIterator:迭代器接口,用于遍历集合中的元素,ListIterator还支持双向...

    Java定时执行某个任务

    总结起来,Java提供了`Timer`和`ScheduledExecutorService`两种方式来实现定时执行任务。`Timer`适合简单的定时任务,而`ScheduledExecutorService`更适合复杂的需求,如多线程环境和高并发场景。选择哪种方式取决于...

    Timer-java.rar_java timer_timer_timer java

    在Java编程语言中,`Timer`类是Java.util包下的一个关键组件,它主要用于调度周期性的任务执行。这个`Timer`类提供了定时器的功能,能够按照预设的时间间隔执行任务,比如更新UI、执行定时检查等。在描述中提到的是...

    使用java.util.Timer实现任务调度

    请注意,`java.util.Timer` 在高并发环境下可能不是最佳选择,因为它使用单线程模型,可能导致任务执行顺序混乱。在更复杂的场景下,可以考虑使用 `java.util.concurrent.ScheduledExecutorService`,它提供了更强大...

    java轻松实现—定时任务

    在Java中,我们可以利用`java.util.Timer`类和`java.util.TimerTask`类来实现简单的定时任务,但这种实现方式存在线程安全问题。在Web应用中,我们可以利用Servlet容器提供的特性来更优雅地处理定时任务,这就是描述...

    java定时执行代码.

    Java提供了多种实现定时任务的机制,这里主要介绍两种:Java.util.Timer类和java.util.concurrent.ScheduledExecutorService接口。 1. Java.util.Timer类: Timer类是Java早期提供的定时任务工具,它可以安排在...

    java 定时执行任务

    在Java中,有两种主要的方式来实现定时任务:Java.util.Timer类和java.util.concurrent包下的ScheduledExecutorService接口。下面我们将详细探讨这两种方法。 1. Java.util.Timer类和TimerTask `Timer`类是Java早期...

    Java里timer执行定时任务

    在这种情况下,可以使用Servlet容器提供的定时任务机制来代替标准的 `java.util.Timer` 类。通常做法是在 Servlet 的 `init()` 方法中安排定时任务,这样可以确保任务与 Web 应用程序的生命周期同步。 例如,可以在...

    java定时任务

    java提供了多种方式来实现定时任务,包括使用java.util.Timer和java.util.TimerTask类、使用java.lang.Thread类的sleep方法、使用java.util.concurrent.ScheduledExecutorService类等。 在本例子中,使用的是java....

    java定时任务调度之Timer 简单示例

    首先,`Timer`类提供了计划任务的能力,它可以按照预定的时间间隔安排任务执行。创建一个`Timer`对象后,你可以使用`schedule()`或`scheduleAtFixedRate()`方法来安排任务。`schedule()`方法用于单次延迟执行,而`...

    Java定时执行任务的三种方法

    `java.util.Timer`类是最基础的定时任务工具,它允许我们创建一个Timer对象并安排任务执行。在创建Timer实例后,通过`schedule`方法可以设置定时任务。例如: ```java Timer timer = new Timer(); timer....

    java定时执行方法&节拍器

    总结一下,Java中实现定时任务主要依靠`java.util.Timer`、`java.util.concurrent.ScheduledExecutorService`等原生API,以及一些第三方库如Quartz。在实际开发中,选择合适的定时任务解决方案需要考虑项目的复杂性...

    java 定时任务及jar包

    在Java中,我们可以使用内置的`java.util.Timer`类和`java.util.concurrent.ScheduledExecutorService`来实现定时任务。这两个工具提供了不同的调度策略,可以根据实际需求选择合适的。 1. `java.util.Timer` 和 `...

    java定时任务,每天定时执行任务

    - **日志记录**:通过记录日志可以帮助调试定时任务,尤其是当任务执行出现异常时。 #### 五、总结 通过以上步骤,我们可以实现在Java Web应用中每天定时执行特定任务的需求。这种方法简单易行,并且具有良好的...

    schedule

    在Java中,`java.util.Timer`是一个用于安排定时任务执行的工具类,而`java.util.TimerTask`则是实际执行的任务对象。`java.util.Timer`通过`schedule`方法来安排定时任务的执行时间。 #### 2. 使用`java.util....

    java每天实现定点执行任务

    要完成这样的功能,我们通常会利用Java的定时任务框架,如`java.util.Timer`类、`java.util.concurrent.ScheduledExecutorService`或者更高级的Quartz库。以下将详细介绍如何使用这些方法来实现每日定时任务。 1. *...

    java定时器代码

    它使用`java.util.TimerTask`作为任务的具体实现类,通过`Timer`调度`TimerTask`来完成定时任务的执行。 #### 三、`java.util.Timer`与`java.util.TimerTask`详解 ##### 3.1 `java.util.Timer` `Timer`类是Java...

Global site tag (gtag.js) - Google Analytics