-
-
Save Emmunaf/a6ac80ebd5dbabbd4898259d873c640b to your computer and use it in GitHub Desktop.
Scheduling a periodic task using ScheduledExecutorService.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
public class AppConfig { | |
@Bean | |
public ScheduledExecutorService getScheduledExecutorService() { | |
return Executors.newSingleThreadScheduledExecutor(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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