简体   繁体   English

Java中C#中的Timer等价?

[英]Equivalent of Timer in C# in Java?

In C#, the timer will trigger an event at a specific interval when enabled. 在C#中,计时器将在启用时以特定间隔触发事件。 How do I achieve this in Java? 我如何用Java实现这一目标?

I want to make a method to be run at a specific interval. 我想让一个方法以特定的间隔运行。 I know how to do this in C#, but not Java. 我知道如何在C#中执行此操作,但不知道Java。

Code in C#: C#中的代码:

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

I tried Timer and TimerTask , but I am not sure whether the method will run when other methods are running. 我尝试过TimerTimerTask ,但我不确定该方法是否会在其他方法运行时运行。

You are looking at the right classes. 你正在寻找合适的班级。 The Timer and TimerTask are the right ones, and they will run in the background if you use them something like this: TimerTimerTask是正确的,如果您使用它们,它们将在后台运行:

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

One way is to use the ExecutorService : 一种方法是使用ExecutorService

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

You can use the codeplex library to implement this. 您可以使用codeplex库来实现此目的。

Schedule a task to run every second with initial delay of 5 seconds 安排任务以每秒运行一次,初始延迟为5秒

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

Schedule a task to run everyday at 3 AM 安排任务每天凌晨3点运行

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

You can use javax.swing.Timer . 您可以使用javax.swing.Timer It has delay in constructor: 它在构造函数中有delay

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM