1 21 package net.sf.hajdbc.util.concurrent; 22 23 import java.text.ParseException ; 24 import java.util.Date ; 25 import java.util.concurrent.CancellationException ; 26 import java.util.concurrent.ExecutionException ; 27 import java.util.concurrent.RejectedExecutionException ; 28 import java.util.concurrent.RejectedExecutionHandler ; 29 import java.util.concurrent.ScheduledThreadPoolExecutor ; 30 import java.util.concurrent.TimeUnit ; 31 32 import org.quartz.CronTrigger; 33 import org.slf4j.Logger; 34 import org.slf4j.LoggerFactory; 35 36 42 public class CronThreadPoolExecutor extends ScheduledThreadPoolExecutor implements CronExecutorService 43 { 44 protected static Logger logger = LoggerFactory.getLogger(CronThreadPoolExecutor.class); 45 46 51 public CronThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) 52 { 53 super(corePoolSize, DaemonThreadFactory.getInstance(), handler); 54 } 55 56 60 public CronThreadPoolExecutor(int corePoolSize) 61 { 62 super(corePoolSize, DaemonThreadFactory.getInstance()); 63 } 64 65 68 public void schedule(final Runnable task, String expression) 69 { 70 if (task == null) throw new NullPointerException (); 71 72 final CronTrigger trigger = new CronTrigger(); 73 74 try 75 { 76 trigger.setCronExpression(expression); 77 } 78 catch (ParseException e) 79 { 80 throw new RejectedExecutionException (e); 81 } 82 83 this.setCorePoolSize(this.getCorePoolSize() + 1); 84 85 Runnable scheduleTask = new Runnable () 86 { 87 90 public void run() 91 { 92 Date fireTime = trigger.getFireTimeAfter(new Date ()); 93 94 try 95 { 96 while (fireTime != null) 97 { 98 long delay = Math.max(fireTime.getTime() - System.currentTimeMillis(), 0); 99 100 try 101 { 102 CronThreadPoolExecutor.this.schedule(task, delay, TimeUnit.MILLISECONDS).get(); 103 104 fireTime = trigger.getFireTimeAfter(new Date ()); 105 } 106 catch (ExecutionException e) 107 { 108 logger.warn(e.toString(), e.getCause()); 109 } 110 } 111 } 112 catch (RejectedExecutionException e) 113 { 114 } 116 catch (CancellationException e) 117 { 118 } 120 catch (InterruptedException e) 121 { 122 } 124 } 125 }; 126 127 this.execute(scheduleTask); 128 } 129 } 130 | Popular Tags |