I need to create a thread, which everyday checks whether I have to create the tasks for this user or not. I know to create and run java threads by using main(). But how to run it in web application. Seriously I searched a lot and didn't get any answer for running in web application. I have few questions regarding this.
1 How my thread will initially start and from where it will run?
2 Do I need to define my thread in any XML file ?
This is my thread
public class TaskGenerationThread implements Runnable {
@Override
public void run(){
System.out.println("callled at "+ new Date());
/*try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
/*List<Users> listOfCA = complianceUserService.getAllCA();
if(listOfCA !=null && !listOfCA.isEmpty()){
Users ca = complianceUserService.fetchUserByUserId(1).get(0);
Date currentDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); //getting first day of month
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); //getting last day of month
Date nextMonthLastDay = calendar.getTime();
taskGeneratorService.generateCronJobTaskForCompanyCompliance(nextMonthFirstDay,nextMonthLastDay,ca);
}*/
}
}
I did this way. Implemented ServletContextListener and passed my Thread object. But didnt work
public class ThreadImplementation implements ServletContextListener{
ScheduledExecutorService listChecker =null;
@Override
public void contextInitialized(ServletContextEvent sce){
listChecker = Executors.newScheduledThreadPool(1);
listChecker.scheduleAtFixedRate(new TaskGenerationThread(), 01, 01, TimeUnit.SECONDS);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
if (listChecker != null) {
listChecker.shutdownNow();
try {
listChecker.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Any help will be highly appreciated. Thank you