TracerScheduleExecutorService extends TracedExecutorService implements
                                                                        ScheduledExecutorService { @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { SofaTracerRunnable r = new SofaTracerRunnable(command, this.traceContext); return getScheduledExecutorService().schedule(r, delay, unit); } TracerScheduleExecutorService(ScheduledExecutorService delegate);  TracerScheduleExecutorService(ScheduledExecutorService delegate,
                                         SofaTraceContext traceContext); @Override ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); @Override ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period,
                                                  TimeUnit unit); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,
                                                     long delay, TimeUnit unit);  }
@Test public void scheduleRunnable() throws InterruptedException { final Map<String, Integer> taskMap = new HashMap<String, Integer>(); taskMap.put("key", 1); SofaTracerRunnable sofaTracerRunnable = new SofaTracerRunnable(new Runnable() { @Override public void run() { taskMap.put("key", taskMap.get("key") + 1); } }); tracerScheduleExecutorService.schedule(sofaTracerRunnable, 1000, TIME_UNIT); Thread.sleep(1100); Integer result = taskMap.get("key"); Assert.assertTrue(result == 2); }
@Test public void scheduleRunnable_with_tracerContext() throws Exception { SofaTraceContext sofaTraceContext = new SofaTracerThreadLocalTraceContext(); sofaTraceContext.push(sofaTracerSpan); final Map<String, Integer> taskMap = new HashMap<String, Integer>(); taskMap.put("key", 1); SofaTracerRunnable sofaTracerRunnable = new SofaTracerRunnable(new Runnable() { @Override public void run() { taskMap.put("key", taskMap.get("key") + 1); } }, sofaTraceContext); tracerScheduleExecutorService.schedule(sofaTracerRunnable, 1000, TIME_UNIT); Thread.sleep(1100); Integer result = taskMap.get("key"); Assert.assertTrue(result == 2); Field field = sofaTracerRunnable.getClass().getDeclaredField("traceContext"); field.setAccessible(true); SofaTraceContext resultSofaTraceContext = (SofaTraceContext) field.get(sofaTracerRunnable); SofaTracerSpan currentSpan = resultSofaTraceContext.getCurrentSpan(); Assert.assertTrue(currentSpan.getOperationName().equals("SofaTracerSpanTest")); }
@Test public void scheduleCallable() throws Exception { final Object testObj = new Object(); ScheduledFuture schedule = tracerScheduleExecutorService .schedule(()-> testObj, 1000, TIME_UNIT); Thread.sleep(1100); Object o = schedule.get(); Assert.assertTrue(testObj == o); }