下面的列子很详细,是关于定时向服务器上传文件的列子简单的4步就可以实现:
1:首先创建动作bean
package com.sun.time2;
public class UploadFile{
/**
*实现上传的代码s省略 可以看下我下面的2篇日志
http://blog.163.com/sun__haiming/blog/static/1283090682009918102455128/ 使用smarupload 实现上传下载[有例子]
http://blog.163.com/sun__haiming/blog/static/128309068201011111948862/ 使用Struts2多文件上传
*/
public void upload()
{
System.out.println("系统自动的上传文件了");
}
}
2.创建定时器MyTaker并完成相应的功能
package com.sun.time2;
import java.util.Calendar;
import java.util.TimerTask;
import javax.servlet.ServletContext;
public class MyTaker extends TimerTask {
private static boolean isRun = false;
private ServletContext context ;
private Calendar ca = Calendar.getInstance();
public MyTaker(ServletContext context)
{
this.context = context;
}
@Override
public void run() {
if(!isRun){
if(19==ca.get(Calendar.MINUTE)){
isRun = true;
context.log("正在执行所加载的任务");
UploadFile uf= new UploadFile();
uf.upload();
isRun =false;
context.log("任务顺利完成");
}
}
else
{
System.out.println("任务还没有执行完毕");
}
}
}
3.创建监听器ContextListener
package com.sun.time2;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.sun.time2.MyTaker;
import java.util.*;
public class ContexListener implements ServletContextListener{
private Timer timer = null;
@Override
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("任务列表已经销毁了");
}
@Override
public void contextInitialized(ServletContextEvent event) {
timer = new Timer(true);
event.getServletContext().log("服务器已经启动了");
timer.schedule(new MyTaker(event.getServletContext()), 0 ,90);///每隔多长时间检查扫描一次
event.getServletContext().log("已经加载了任务的列表");
}
}
4,最后一步就是在web.xml中配置监听
<!-- Java定时器 -->
<listener>
<listener-class>com.sun.time2.ContexListener</listener-class>
</listener>