Skip to content

Instantly share code, notes, and snippets.

@piyusht007
Last active May 13, 2022 16:54
Show Gist options
  • Save piyusht007/15dc4d27521f8b30e53869d661719a1d to your computer and use it in GitHub Desktop.
Save piyusht007/15dc4d27521f8b30e53869d661719a1d to your computer and use it in GitHub Desktop.
Scheduling a periodic task using ScheduledExecutorService.
@Configuration
public class AppConfig {
@Bean
public ScheduledExecutorService getScheduledExecutorService() {
return Executors.newSingleThreadScheduledExecutor();
}
}
@Component
public class SomeReloadService {
@Autowired
private ScheduledExecutorService executor;
@Autowired
private SomeDependency someDependency;
/**
* Schedule some task here.
*/
public void scheduleSomeReloadTask() {
executor.scheduleAtFixedRate(() -> {
// Your task.
someDependency.doSomething();
}, 0, 1, TimeUnit.DAYS);
}
}
public class SomeReloadServiceTest {
@Mock
private ScheduledExecutorService executor;
@Mock
private SomeDependency someDependency;
@InjectMocks
private SomeReloadService someReloadService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testScheduleSomeReloadTask(){
// Given
final ArgumentCaptor<Runnable> argumentCaptor = ArgumentCaptor.forClass(Runnable.class);
// When
someReloadService.scheduleSomeReloadTask();
// Then
Mockito.verify(executor, Mockito.times(1)).scheduleAtFixedRate(argumentCaptor.capture(), Mockito.eq(0l), Mockito.eq(1l), Mockito.eq(TimeUnit.DAYS));
argumentCaptor.getAllValues().get(0).run();
Mockito.verify(someDependency, Mockito.times(1)).doSomething();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment