如何在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(); } } 

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

使用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 ); } 

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

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

您可以使用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); 

你可以使用类Timer

从文档:

线程的工具,用于在后台线程中安排将来执行的任务。 可以将任务安排为一次性执行,或者以固定间隔重复执行。

方法schedule(TimerTask task, Date time)正是您想要的:计划指定任务在指定时间执行。

如果您需要以cron格式安排, 石英将是一个很好的解决方案。 ( 石英cron像时间表 )

如果您正在谈论SE,那么Timer类可能就是您正在寻找的http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html ,自Java 5开始提供。

如果您需要在应用程序服务器上下文中计时,我建议您查看EJB计时器http://www.javabeat.net/2007/03/ejb-3-0-timer-services-an-overview/ EJB 3.0。

或者,根据您真正想要做的事情,您可以详细说明使用cron作业(或任何其他基于操作系统的计时器方法)是否更合适,即您不希望或不能让VM运行所有时间。

据我所知,你可以使用Quartz-scheduler 。 我还没用过它,但很多人都向我推荐过它。

有可能的。 您可以使用TimerTimerTask在某个时间安排方法。

例如:

 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 10); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 0); Date alarmTime = calendar.getTime(); Timer _timer = new Timer(); _timer.schedule(foo, alarmTime); 

请参考这些链接:

  • 计时器
  • 的TimerTask

java.util.Timer的简单演示

 Timer t=new Timer(); t.schedule(new TimerTask() { public void run() { foo(); } }, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-07-06 13:40:20"));