C#中的计时器在Java中有什么等价物?

5

在C#中,启用计时器后,它会在特定间隔时间内触发一个事件。那么我如何在Java中实现这个功能呢?

我想要创建一个方法,在特定的时间间隔内运行该方法。虽然我知道如何在C#中实现此功能,但并不知道如何在Java中实现。

C#中的代码:

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

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


你可以使用 https://timerutil.codeplex.com/。 - PC.
4个回答

6

您需要查看正确的类。 TimerTimerTask 就是正确的类,如果您像这样使用它们,它们将在后台运行:

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

3

一种方法是使用 ExecutorService

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

1
你可以使用codeplex库来实现这一点。 安排一个任务每秒运行一次,初始延迟为5秒
new Timer().Schedule(DoSomething, 5000, 1000);

安排一个任务每天早上3点运行。
new Timer().Schedule(DoSomething, Timer.GetFutureTime(3), Timer.MILLISECONDS_IN_A_DAY);

0
你可以使用 javax.swing.Timer。它在构造函数中有delay
Timer timer = new Timer(DELAY_IN_MILLISECONDS_INT, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //some code here
    }
});

你不应该使用这个。这些来自swing包,这真的不是你想要的。 - Erik Pragt
为什么不呢?我这里没有看到任何问题。 - Dmitry Ginzburg
1
它增加了 Swing 的不必要依赖。 - Chris Mantle
Swing是默认JRE的一部分。因此,这种依赖关系不会导致任何努力,对吧? - Dmitry Ginzburg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接