How to start method in background after spring app starts
I have method that perform Url scan and I need to initiate it in backround
after all spring configurations are loaded. I tryed to use
InitializingBean, but process goes to loop not in background and
configuration never ends. Please give me any sugession on this issue.
Thank you.
@Component
public class ScheduledScanner implements InitializingBean {
protected static Logger logger =
Logger.getLogger(ScheduledScanner.class);
protected final static String USER_AGENT = "Mozilla/5.0 (Windows NT
6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0";
private static final int MYTHREADS = 30;
private Date date = new Date();
private Timestamp timestamp = new Timestamp(date.getTime());
private AdminService adminService;
private EmployeeService employeeService;
private ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext(new
String[]{"classpath:application-context.xml"});
@Autowired
public void setAdminService(AdminService adminService) {
this.adminService = adminService;
}
@Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
/**
* Sends GET request to @param ip: @param port with Apache HttpClient
* <p/>
* param ip - must contain URL or IP of target server;
* param port - for server target Port;
* param timeout - sets the time for request timeout before no respond;
* <p/>
* ServerState enum:
* OK - server is up and responding correctly
* WARN - server is running, but returns a response to the HTTP -
code different than 200
* FAIL - the server is not responding, or responds with HTTP code,
such as 500
* <p/>
* - all other info:
http://docs.oracle.com/javaee/6/api/javax/ws/rs/core/Response.Status.html
*/
public void afterPropertiesSet() throws Exception {
logger.debug("ServletContextListener started");
final List<ServerEntity> listToScan = adminService.getAllServers();
final SystemSettingsModel settings =
employeeService.getSettingsByName("default");
// setting task to execute;
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(MYTHREADS);
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// iterating list of all servers
for (ServerEntity serverEntity : listToScan) {
// check if state of server is active
if (serverEntity.getActive().equals(1)) {
ServerState state;
try {
// setting URL or IP eith Port of target address
URL obj = new URL(serverEntity.getAddress() +
":" + serverEntity.getPort());
// establishing connection
HttpURLConnection con = (HttpURLConnection)
obj.openConnection();
con.setRequestMethod("GET");
// setting timeout of response
con.setConnectTimeout(settings.getTimeoutOfRespond());
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
if (con.getResponseCode() == 200) {
state = ServerState.OK;
} else if (con.getResponseCode() == 500) {
state = ServerState.FAIL; // Internal
Server Error
} else {
state = ServerState.WARN; // BAD_REQUEST
or other conflict
}
} catch (Exception e) {
state = ServerState.FAIL;
}
// saving response from server
serverEntity.setState(state);
serverEntity.setResponse(state.toString());
serverEntity.setLastCheck(timestamp);
adminService.updateServer(serverEntity);
} // if
} // run()
} // for
/*
* Scheduling Fixed Rate of scan
*
* param initialDelay the time to delay first execution;
* param period the period between successive executions;
* param unit the time unit of the initialDelay and period
parameters;
*/
}, 0, settings.getServerScanInterval(), TimeUnit.SECONDS);
} // executeScanner()
}
in the debug, app start to go in loop this line:
(DefaultListableBeanFactory.java:preInstantiateSingletons:596)
Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@410bf486:
defining beans
[org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,adminPasswordUpdateController,adminSettingsController,employeeDeleteController,employeeEditController,employeeManagementController,employeeRegistrationController,serverAssignmentController,serverDeleteController,serverEditController,serverManagementController,serverRegistrationController,employeePasswordUpdateController,serverDetailsController,serverMonitoringController,loginLogoutController,passwordRecoveryController,employeeJdbcDaoSupport,serverJdbcDaoSupport,settingsJdbcDaoSupport,AdminServiceImpl,AnonymousServiceImpl,EmployeeServiceImpl,userAuthentication,customUtilsImpl,CustomMailDeliveryImpl,scheduledScanner,simpleScannerImpl,employeeRegistrationValidator,employeeUpdateV
alidatior,passwordRecoveryValidator,passwordUpdateValidator,serverRegistrationValidator,settingsUpdateValidator,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,txManager,dataSource,org.springframework.jdbc.datasource.init.DataSourceInitializer#0,log4jInitialization,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionRes
olver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.handler.MappedInterceptor#1,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor];
root of factory hierarchy
UPDATED: I removed @Component annotation and it removed loop in config
lines, but method is not looping as it was expected.
No comments:
Post a Comment