我想做一个定时程序,每天某一个时间定时执行程序,从网上搜了一段代码不执行是怎么回事?还需要在web.xml里做设置吗,怎么设置,我设置了也不执行。代码如下: 
package com.timer.test; import java.util.Calendar; 
import java.util.Date; 
import java.util.Timer; 
import java.util.TimerTask; /**** 
* TimerTask与Timer 

* @author bruceleey 

*/ 
public class TestTimer { 
    static int count = 0;     public static void showTimer() { 
        TimerTask task = new TimerTask() { 
            @Override 
            public void run() { 
                ++count; 
                System.out.println("count执行了-->" + count); // 1次 
            }         };         Calendar calendar = Calendar.getInstance(); 
        int year = calendar.get(Calendar.YEAR); 
        int month = calendar.get(Calendar.MONTH); 
        int day = calendar.get(Calendar.DAY_OF_MONTH) - 1; 
        /*** 定制每日00:24:00执行方法 ***/ 
        calendar.set(year, month, day, 24, 24, 00); 
        Date date = calendar.getTime(); 
        Timer timer = new Timer(); 
        timer.schedule(task, date); 
    }     public static void main(String[] args) { 
        showTimer(); 
    } }

解决方案 »

  1.   

    直接上段代码你看下
    class MyTask extends TimerTask {
    public MyTask() {
    };
    public void run() {
    // do somthing
    System.out.println("new task is working !!");
    }
    }
    class Test extends Thread{
    public Test() {
    }
    public void run() {
    MyTask myTask = new MyTask();
    Timer timer = new Timer(true);
    timer.schedule(myTask, 0, 5*1000);
    while (true) {
    try {
    handleRequest();
    Thread.currentThread().sleep(3000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    private void handleRequest() {
    try {
    System.out.println("system in working !");
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    public static void main(String[] args) {
    Test test = new Test();
    test.start();
    }}