直播平台软件开发,JavaWeb如何设置定时任务
直播平台软件开发,JavaWeb如何设置定时任务
1.在xml文件中添加监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>com.tct.test.ContextListener</listener-class>
</listener>
</web-app>
2.编写定时任务Java代码
package com.tct.test;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextListener implements ServletContextListener {
Timer timer = new Timer() ;
public void contextInitialized(ServletContextEvent event) {
timer = new java.util.Timer(true);
event.getServletContext().log("定时器已启动");
timer.schedule(new MyTask(event.getServletContext()), 0,1000);
event.getServletContext().log("已经添加任务调度表");
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器以销毁");
}
}
package com.tct.test;
import java.util.TimerTask;
import javax.servlet.ServletContext;
public class MyTask extends TimerTask {
private static boolean isRunning = false;
private ServletContext context = null;
public MyTask(ServletContext servletContext) {
this.context = servletContext;
}
@Override
public void run() {
if(!isRunning)
{
isRunning = true;
context.log("开始执行指定任务");
isRunning = false;
}
else
{
context.log("上次的任务还未执行完成");
}
}
}
以上就是直播平台软件开发,JavaWeb如何设置定时任务, 更多内容欢迎关注之后的文章