Skip to content

Instantly share code, notes, and snippets.

@anataliocs
Last active January 23, 2018 09:05
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save anataliocs/61291ea9a96f8a642a61 to your computer and use it in GitHub Desktop.
Spring Scheduled task background process to make async call to update cache
@Controller
@Configuration
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
@EnableCaching
@EnableAsync
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Component
public class ScheduledTask {
private static final long RUN_TASK_EVERY_10_SEC = 10000l;
private static final long SLEEP_1_SEC = 1000L;
private final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);
@Autowired
Service service;
@Scheduled(fixedDelay = RUN_TASK_EVERY_10_SEC)
public void updateEndpoints() {
Future<Map<String, String>> status =
service.getEndpointStatus(1);
while (!(status.isDone()) {
Thread.sleep(SLEEP_1_SEC);
}
logger.trace("Do Action here");
}
}
@Service
public class ServiceImpl implements Service {
@Async
@Override
@Cacheable(CacheConfig.HEALTH_CHECK_CACHE)
public Future<Map<String, String>> getEndpointStatus(int serviceName) {
switch (serviceName) {
case :
return getStatus();
}
@Async
private Future<Map<String, String>> getStatus() {
return new AsyncResult<Map<String, String>>(
createStatusMap("test","test123")
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment