1 17 package org.apache.servicemix.components.varscheduler; 18 19 import java.util.Date ; 20 import java.util.Timer ; 21 import java.util.TimerTask ; 22 23 31 public class Scheduler { 32 33 private Timer timer; 34 35 38 public Scheduler() { 39 this.timer = new Timer (); 40 } 41 42 46 public Scheduler(boolean daemon) { 47 this.timer = new Timer (daemon); 48 } 49 50 53 public void cancel() { 54 timer.cancel(); 55 } 56 57 64 public void schedule(SchedulerTask task, ScheduleIterator iterator) { 65 Date time = iterator.nextExecution(); 66 if (time == null) { 67 task.cancel(); 68 } else { 69 synchronized (task.lock) { 70 if (task.state != SchedulerTask.VIRGIN) { 71 throw new IllegalStateException ( 72 "Task already scheduled or cancelled"); 73 } 74 task.state = SchedulerTask.SCHEDULED; 75 task.timerTask = new SchedulerTimerTask(task, iterator); 76 timer.schedule(task.timerTask, time); 77 } 78 } 79 } 80 81 private void reschedule(SchedulerTask task, ScheduleIterator iterator) { 82 Date time = iterator.nextExecution(); 83 if (time == null) { 84 task.cancel(); 85 } else { 86 synchronized (task.lock) { 87 if (task.state != SchedulerTask.CANCELLED) { 88 task.timerTask = new SchedulerTimerTask(task, iterator); 89 timer.schedule(task.timerTask, time); 90 } 91 } 92 } 93 } 94 95 98 class SchedulerTimerTask extends TimerTask { 99 private SchedulerTask task; 100 private ScheduleIterator iterator; 101 102 public SchedulerTimerTask(SchedulerTask task,ScheduleIterator iterator){ 103 this.task = task; 104 this.iterator = iterator; 105 } 106 107 public void run() { 108 task.run(); 109 reschedule(task, iterator); 110 } 111 } 112 113 } 114 115 | Popular Tags |