如何在java中的特定时间调用方法? [英] How to call a method on specific time in java?
本文介绍了如何在java中的特定时间调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在特定时间调用java中的方法?例如,我有一段这样的代码:
Is it possible to call a method in java at specific time? For examplef I have a piece of code like this:
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中完成此操作?
How this can be done in java?
推荐答案
使用 java.util.Timer 类,您可以创建一个计时器并安排它在特定时间运行。
Using a java.util.Timer class you can create a timer and schedule it to run at specific time.
以下是示例:
//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 );
}
这篇关于如何在java中的特定时间调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文