有些时候我们有这样的需求当tomcat启动时候或者关闭的时候我们想要调用某些方法。这个时候就可以这么做。直接贴代码
在web.xml中需要加上
这样我们就可以在tomcat启动时就做我们要做的事情
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
public class MyListener implements ServletContextListener {
private static MyJobScheduler myJobScheduler;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
try {
MyJobScheduler.getScheduler().shutdown();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
myJobScheduler = new MyJobScheduler();
}
}
import java.util.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
public class MyJobScheduler {
private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();
private static Scheduler scheduler = null;
public static Scheduler getScheduler() {
return scheduler;
}
public MyJobScheduler(){
try {
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
static{
try {
scheduler = schedulerFactory.getScheduler();
JobDetail jobDetail = new JobDetail("job1", "jgroup", MyJob.class);
SimpleTrigger simpleTrigger = new SimpleTrigger("simpleTrigger", new Date(), null, SimpleTrigger.REPEAT_INDEFINITELY, Long.parseLong(ReadingProperties.getPp().getProperty("time")));
scheduler.scheduleJob(jobDetail, simpleTrigger);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
在web.xml中需要加上
<listener>
<listener-class>com.energyfuture.action.MyListener</listener-class>
</listener>
这样我们就可以在tomcat启动时就做我们要做的事情