`

定时任务

    博客分类:
  • Java
 
阅读更多
  Java中的定时任务总结:
一、Timer:
   线程用其安排以后在后台线程中执行的任务,可安排任务执行一次,或者定期重复执行。
   注意事项:所有构造方法都启动计时器线程。
定时的方法:
     1、schedule(TimerTask task, Date time)
     安排在指定的时间执行指定的任务。
     2、schedule(TimerTask task, Date firstTime, long period)
     安排指定的任务在指定的时间开始进行重复的固定延迟执行。
     3、schedule(TimerTask task, long delay)
     安排在指定延迟后执行指定的任务。
     4、schedule(TimerTask task, long delay, long period)
     安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。
     5、scheduleAtFixedRate(TimerTask task,Date firstTime,long period)
    安排指定的任务在指定的时间开始进行重复的固定速率执行。
    6、scheduleAtFixedRate(TimerTask task, long delay, long period)
    安排指定的任务在指定的延迟后开始进行重复的固定速率执行。

简单的应用:
      Timer timer = new Timer();
     timer.scheduleAtFixedRate(new SchedulTask(), 1000, 3000);

二、实现ScheduledExecutorService接口:
    安排在给定的延迟后运行或定期执行的命令。
    Executors 类为此包中所提供的 ScheduledExecutorService 实现提供了便捷的工厂方法。
执行方法如下:
   1、schedule(Callable<V> callable, long delay, TimeUnit unit)
     创建并执行在给定延迟后启用的 ScheduledFuture。
   2、ScheduledFuture<?> schedule(Runnable command, long delay,
TimeUnit unit)
     创建并执行在给定延迟后启用的一次性操作。
   3、ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
     创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在 initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。
   4、ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
    创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。

简单一个应用:
  ScheduledExecutorService
           schedule =   Executors.newScheduledThreadPool(1);
           schedule.scheduleAtFixedRate(
new Runnable(){
public void run(){
System.out.println("定时!!!");
}},
1,
2,
TimeUnit.SECONDS);
注:ScheduledThreadPoolExecutor实现了ScheduledExecutorService接口,和上面类似。

 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics