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

Sam*_*ami 28 java

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

class Test{
 ....
// parameters 
....

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

如何在java中完成这项工作?

Ram*_*PVK 50

使用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 );
}
Run Code Online (Sandbox Code Playgroud)

  • Timer的javadoc建议使用Java 5中引入的“ ScheduledThreadPoolExecutor”:http://stackoverflow.com/a/11361397/829571 (2认同)

ass*_*ias 7

你可以使用一个ScheduledExecutorService的,这是"更通用的更换为Timer/ TimerTask组合"(据Timer的的Javadoc):

long delay = ChronoUnit.MILLIS.between(LocalTime.now(), LocalTime.of(13, 5, 45));
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 6

它是可能的,我会使用像http://quartz-scheduler.org/这样的库

Quartz是一个功能齐全的开源作业调度服务,可以与几乎任何Java EE或Java SE应用程序集成或一起使用 - 从最小的独立应用程序到最大的电子商务系统.Quartz可用于创建简单或复杂的计划,以执行数十,数百甚至数万个作业; 将任务定义为标准Java组件的作业,这些组件可以执行几乎任何可以编程的程序.