我需要创建一个线程,每天检查是否必须为此用户创建任务。我知道使用main()
创建和运行java线程。但是如何在Web应用程序中运行它。说真的,我搜索过很多,并没有得到任何在网络应用程序中运行的答案。我对此几乎没有任何疑问。
1 我的帖子最初start
的方式以及run
的位置?
2 我是否需要在任何XML文件中定义我的线程?
这是我的主题
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);
}*/
}
}
我是这样做的。实现了ServletContextListener
并传递了我的Thread对象。但没有工作
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();
}
}
}
}
任何帮助都将受到高度赞赏。谢谢
答案 0 :(得分:1)
写一个
的课程implements ServletContextListener
覆盖
public void contextInitialized(ServletContextEvent sce)
从这里启动一些调度程序
e.g。
listChecker = Executors.newScheduledThreadPool(1);
listChecker.scheduleAtFixedRate(filechecker, 60, 60, TimeUnit.SECONDS);
注意这适用于Tomcat
您的contextDestroyed
应该是
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("Scheduler entered contextDestroyed");
if (listChecker != null) {
listChecker.shutdownNow();
log.info("waiting [60 seconds] for collector threads to finsih");
try {
listChecker.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info("Scheduler finished contextDestroyed");
}
当然,您需要将其添加到web.xml
<listener>
<listener-class>
myPackage.Scheduler
</listener-class>
</listener>