tomcat 定时任务 嵌入tomcat自动启动
好多混经验的帖子,然后这都是千篇一律的抄袭一篇,烦不胜烦,保存下来防止以后忘记
创建ScheduleListener 类
代码如下(示例):
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/schedule")
public class ScheduleListener implements ServletContextListener
{
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
Runnable runnable = new Runnable() {
int i=0;
public void run() {
// task to run goes here
i=i+1;
System.out.println( "------------------------执行" + i);
//就可以调用自己的方法执行了
}
};
ScheduledExecutorService service = Executors
.newSingleThreadScheduledExecutor();
// 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间 单位秒
service.scheduleAtFixedRate(runnable, 1 , 5 , TimeUnit.SECONDS);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}
然后在web.xml
<listener>
//注意这里配置的是ScheduleListener.class路径名
<listener-class>com.test.quartz.job.ScheduleListener</listener-class>
</listener>