servlet上加定时任务

1、servlet启动后自动会运行
将此段代码放入建立的servlet里面(dopost,doget)

public void destroy() {  
        super.destroy();   
    }  

    public void init() throws ServletException {  
        System.out.println("加载网站首页生成任务");  
        this.timerTask();  
    }  

    public static void timerTask() {  
        int i=0;
        new Timer().schedule(new TimerTask(){  
            @Override  
            public void run() {  

                System.out.println("成功---");  
            }  
        },new Date(),60*60*1000);  //1000为1秒 
        i++;
        System.out.println("i="+i);  
   } 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java web中的监听器(Listener)来实现定时任务的调度。具体来说,可以使用ServletContextListener监听器来实现在Web应用程序启动时启动定时任务,使用ServletContextAttributeListener监听器来实现在Web应用程序中添加、修改或删除定时任务时调度任务。以下是具体的实现步骤: 1. 创建一个定时任务类,实现Servlet接口,并在其中编写定时任务逻辑。例如: ```java public class MyTask implements Servlet { public void init(ServletConfig config) throws ServletException { // 初始化定时任务 } public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // 定时任务逻辑 } public void destroy() { // 结束定时任务 } } ``` 2. 创建一个ServletContextListener监听器,在其中初始化定时任务并启动它。例如: ```java public class MyListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { // 初始化定时任务 MyTask task = new MyTask(); task.init(event.getServletContext().getServletConfig()); // 启动定时任务 Timer timer = new Timer(); timer.schedule(task, 0, 1000); // 每隔1秒执行一次 } public void contextDestroyed(ServletContextEvent event) { // 结束定时任务 MyTask task = new MyTask(); task.destroy(); } } ``` 3. 在web.xml文件中配置监听器。例如: ```xml <listener> <listener-class>com.example.MyListener</listener-class> </listener> ``` 这样,在Web应用程序启动时,MyListener监听器会自动启动定时任务,并在Web应用程序关闭时结束任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值