Java中C#中的Timer等价?

在C#中,计时器将在启用时以特定间隔触发事件。 我如何用Java实现这一目标?

我想让一个方法以特定的间隔运行。 我知道如何在C#中实现这一点,而不是Java。

C#中的代码:

private void timer1_Tick(object sender, EventArgs e) { //the method } 

我尝试了TimerTimerTask ,但我不确定该方法是否会在其他方法运行时运行。

你正在寻找合适的class级。 Timer和TimerTask是正确的,如果您使用它们,它们将在后台运行:

 TimerTask task = new RunMeTask(); Timer timer = new Timer(); timer.schedule(task, 1000, 60000); 

一种方法是使用ExecutorService :

 Runnable task = new Runnable() { @Override public void run() { // your code } }; ScheduledExecutorService service = Executors.newScheduledThreadPool(1); service.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.Seconds); 

您可以使用codeplex库来实现此目的。

安排任务以每秒运行一次,初始延迟为5秒

 new Timer().Schedule(DoSomething, 5000, 1000); 

安排任务每天凌晨3点运行

 new Timer().Schedule(DoSomething, Timer.GetFutureTime(3), Timer.MILLISECONDS_IN_A_DAY); 

您可以使用javax.swing.Timer 。 它在构造函数中有delay

 Timer timer = new Timer(DELAY_IN_MILLISECONDS_INT, new ActionListener() { public void actionPerformed(ActionEvent e) { //some code here } });