一尘不染

如何在Java中的特定时间调用方法?

java

是否可以在特定时间在Java中调用方法?例如,我有一段这样的代码:

class Test{

    public static void main(String args[]) {
        // here i want to call foo at : 2012-07-06 13:05:45 for instance
        foo();
    }
}

如何在Java中完成此操作?


阅读 209

收藏
2020-09-08

共1个答案

一尘不染

使用java.util.Timer类,您可以创建计时器并将其计划为在特定时间运行。

下面是示例:

//The task which you want to execute
private static class MyTimeTask extends TimerTask
{

    public void run()
    {
        //write your code here
    }
}

public static void main(String[] args) {

    //the Date and time at which you want to execute
    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = dateFormatter .parse("2012-07-06 13:05:45");

    //Now create the time and schedule it
    Timer timer = new Timer();

    //Use this if you want to execute it once
    timer.schedule(new MyTimeTask(), date);

    //Use this if you want to execute it repeatedly
    //int period = 10000;//10secs
    //timer.schedule(new MyTimeTask(), date, period );
}
2020-09-08