1 16 17 package org.springframework.scheduling.timer; 18 19 import java.util.ArrayList ; 20 import java.util.List ; 21 import java.util.Timer ; 22 import java.util.TimerTask ; 23 24 import junit.framework.TestCase; 25 26 import org.springframework.scheduling.TestMethodInvokingTask; 27 28 32 public class TimerSupportTests extends TestCase { 33 34 public void testTimerFactoryBean() throws Exception { 35 final TestTimerTask timerTask0 = new TestTimerTask(); 36 37 TestMethodInvokingTask task1 = new TestMethodInvokingTask(); 38 MethodInvokingTimerTaskFactoryBean mittfb = new MethodInvokingTimerTaskFactoryBean(); 39 mittfb.setTargetObject(task1); 40 mittfb.setTargetMethod("doSomething"); 41 mittfb.afterPropertiesSet(); 42 final TimerTask timerTask1 = (TimerTask ) mittfb.getObject(); 43 44 final TestTimerTask timerTask2 = new TestTimerTask(); 45 46 ScheduledTimerTask[] tasks = new ScheduledTimerTask[3]; 47 tasks[0] = new ScheduledTimerTask(timerTask0, 0, 10, false); 48 tasks[1] = new ScheduledTimerTask(timerTask1, 10, 20, true); 49 tasks[2] = new ScheduledTimerTask(timerTask2, 20); 50 51 final List success = new ArrayList (3); 52 final Timer timer = new Timer (true) { 53 public void schedule(TimerTask task, long delay, long period) { 54 if (task == timerTask0 && delay == 0 && period == 10) { 55 success.add(Boolean.TRUE); 56 } 57 } 58 public void scheduleAtFixedRate(TimerTask task, long delay, long period) { 59 if (task == timerTask1 && delay == 10 && period == 20) { 60 success.add(Boolean.TRUE); 61 } 62 } 63 public void schedule(TimerTask task, long delay) { 64 if (task == timerTask2 && delay == 20) { 65 success.add(Boolean.TRUE); 66 } 67 } 68 public void cancel() { 69 success.add(Boolean.TRUE); 70 } 71 }; 72 73 TimerFactoryBean timerFactoryBean = new TimerFactoryBean() { 74 protected Timer createTimer(boolean daemon) { 75 return timer; 76 } 77 }; 78 try { 79 timerFactoryBean.setScheduledTimerTasks(tasks); 80 timerFactoryBean.afterPropertiesSet(); 81 assertTrue(timerFactoryBean.getObject() instanceof Timer ); 82 timerTask0.run(); 83 timerTask1.run(); 84 timerTask2.run(); 85 } 86 finally { 87 timerFactoryBean.destroy(); 88 } 89 90 assertTrue("Correct Timer invocations", success.size() == 4); 91 assertTrue("TimerTask0 works", timerTask0.counter == 1); 92 assertTrue("TimerTask1 works", task1.counter == 1); 93 assertTrue("TimerTask2 works", timerTask2.counter == 1); 94 } 95 96 97 private static class TestTimerTask extends TimerTask { 98 99 private int counter = 0; 100 101 public void run() { 102 counter++; 103 } 104 } 105 106 } 107 | Popular Tags |