java 几种常见的定时器

今天闲着没事就总结了一下在java中常用的几种定时器。

主要有3种java.util.Timer, ScheduledExecutorService和quartz

一.Timer

   举个简单例子。每隔5秒自动刷新。

[java] view plaincopy
 
  1. Timer timerFresh = new Timer();  
  2.         timerFresh.schedule(new TimerTask() {  
  3.             public void run() {  
  4.                Display.getDefault().syncExec(new Runnable() {  
  5.                    public void run() {  
  6.                    setInputValue();//这里写你的方法,就可以了。   
  7.                    }  
  8.                });  
  9.             }  
  10.         }, 5000, 5000);  

二.ScheduledExecutorService

ScheduledExecutorService
schedule(Runnablecommand, long delay, TimeUnitunit) : ScheduledFuture
schedule(Callable<V> callable, long delay, TimeUnitunit) : ScheduledFuture
scheduleAtFixedRate(Runnablecomand, long initDelay, long period, TimeUnitunit) : ScheduledFuture
scheduleWithFixedDelay(Runnablecommand, long initDelay, long delay, TimeUnitunit) :

ScheduledFuturejava.util.concurrent.Executors是ScheduledExecutorService的工厂类,通过Executors,你可以创建你所需要的ScheduledExecutorService。JDK 1.5之后有了ScheduledExecutorService,不建议你再使用java.util.Timer,因为它无论功能性能都不如ScheduledExecutorService。
ScheduledExecutorService
ScheduledTaskSubmitter
ScheduleFuture<Object> future = scheduler.schedule(task, 1, TimeUnit.SECONDS);
// 等待到任务被执行完毕返回结果
// 如果任务执行出错,这里会抛ExecutionException
future.get();
//取消调度任务
future.cancel();

ScheduledFuturejava.util.concurrent.Executors是ScheduledExecutorService的工厂类,通过Executors,你可以创建你所需要的ScheduledExecutorService。JDK 1.5之后有了ScheduledExecutorService,不建议你再使用java.util.Timer,因为它无论功能性能都不如ScheduledExecutorService。

比如这篇文章讲的很好。

在Timer和ScheduledExecutorService间决择

http://sunnylocus.javaeye.com/blog/530969

三.quartz

    这个目前考虑的比较全面用的比较多。

[java] view plaincopy
 
  1. /*  
  2.  * Copyright 2005 OpenSymphony  
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not  
  5.  * use this file except in compliance with the License. You may obtain a copy  
  6.  * of the License at  
  7.  *  
  8.  *   http://www.apache.org/licenses/LICENSE-2.0  
  9.  *    
  10.  * Unless required by applicable law or agreed to in writing, software  
  11.  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT  
  12.  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the  
  13.  * License for the specific language governing permissions and limitations  
  14.  * under the License. 
  15.  *  
  16.  */  
  17.   
  18. package org.quartz.examples.example4;  
  19.   
  20. import java.util.Date;  
  21.   
  22. import org.apache.commons.logging.Log;  
  23. import org.apache.commons.logging.LogFactory;  
  24. import org.quartz.JobDetail;  
  25. import org.quartz.Scheduler;  
  26. import org.quartz.SchedulerFactory;  
  27. import org.quartz.SchedulerMetaData;  
  28. import org.quartz.SimpleTrigger;  
  29. import org.quartz.TriggerUtils;  
  30. import org.quartz.impl.StdSchedulerFactory;  
  31.   
  32. /** 
  33.  * This Example will demonstrate how job parameters can be  
  34.  * passed into jobs and how state can be maintained 
  35.  *  
  36.  * @author Bill Kratzer 
  37.  */  
  38. public class JobStateExample {  
  39.   
  40.     public void run() throws Exception {  
  41.         Log log = LogFactory.getLog(JobStateExample.class);  
  42.   
  43.         log.info("------- Initializing -------------------");  
  44.   
  45.         // First we must get a reference to a scheduler  
  46.         SchedulerFactory sf = new StdSchedulerFactory();  
  47.         Scheduler sched = sf.getScheduler();  
  48.   
  49.         log.info("------- Initialization Complete --------");  
  50.   
  51.         log.info("------- Scheduling Jobs ----------------");  
  52.   
  53.         // get a "nice round" time a few seconds in the future....  
  54.         long ts = TriggerUtils.getNextGivenSecondDate(null, 10).getTime();  
  55.   
  56.         // job1 will only run 5 times, every 10 seconds  
  57.         JobDetail job1 = new JobDetail("job1", "group1", ColorJob.class);  
  58.         SimpleTrigger trigger1 = new SimpleTrigger("trigger1", "group1", "job1", "group1",  
  59.                 new Date(ts), null, 4, 10000);  
  60.         // pass initialization parameters into the job  
  61.         job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");  
  62.         job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);  
  63.           
  64.         // schedule the job to run  
  65.         Date scheduleTime1 = sched.scheduleJob(job1, trigger1);  
  66.         log.info(job1.getFullName() +  
  67.                 " will run at: " + scheduleTime1 +    
  68.                 " and repeat: " + trigger1.getRepeatCount() +   
  69.                 " times, every " + trigger1.getRepeatInterval() / 1000 + " seconds");  
  70.   
  71.         // job2 will also run 5 times, every 10 seconds  
  72.         JobDetail job2 = new JobDetail("job2", "group1", ColorJob.class);  
  73.         SimpleTrigger trigger2 = new SimpleTrigger("trigger2", "group1", "job2", "group1",  
  74.                 new Date(ts + 1000), null, 4, 10000);  
  75.         // pass initialization parameters into the job  
  76.         // this job has a different favorite color!  
  77.         job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");  
  78.         job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);  
  79.           
  80.         // schedule the job to run  
  81.         Date scheduleTime2 = sched.scheduleJob(job2, trigger2);  
  82.         log.info(job2.getFullName() +  
  83.                 " will run at: " + scheduleTime2 +  
  84.                 " and repeat: " + trigger2.getRepeatCount() +  
  85.                 " times, every " + trigger2.getRepeatInterval() / 1000 + " seconds");   
  86.   
  87.   
  88.         log.info("------- Starting Scheduler ----------------");  
  89.   
  90.         // All of the jobs have been added to the scheduler, but none of the jobs  
  91.         // will run until the scheduler has been started  
  92.         sched.start();  
  93.   
  94.         log.info("------- Started Scheduler -----------------");  
  95.           
  96.         log.info("------- Waiting 60 seconds... -------------");  
  97.         try {  
  98.             // wait five minutes to show jobs  
  99.             Thread.sleep(60L * 1000L);   
  100.             // executing...  
  101.         } catch (Exception e) {  
  102.         }  
  103.   
  104.         log.info("------- Shutting Down ---------------------");  
  105.   
  106.         sched.shutdown(true);  
  107.   
  108.         log.info("------- Shutdown Complete -----------------");  
  109.   
  110.         SchedulerMetaData metaData = sched.getMetaData();  
  111.         log.info("Executed " + metaData.numJobsExecuted() + " jobs.");  
  112.   
  113.     }  
  114.   
  115.     public static void main(String[] args) throws Exception {  
  116.   
  117.         JobStateExample example = new JobStateExample();  
  118.         example.run();  
  119.     }  
  120.   
  121. }  

   需要源码的可以去这里下载 http://dl.dbank.com/c0a4wn14yl

原文地址:https://www.cnblogs.com/Struts-pring/p/4303887.html