Equivalent of Timer in C# in Java?

2019-05-01 10:00发布

In C#, the timer will trigger an event at a specific interval when enabled. How do I achieve this in 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.

Code in 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.

标签: c# java timer
4条回答
等我变得足够好
2楼-- · 2019-05-01 10:32

You can use the codeplex library to implement this.

Schedule a task to run every second with initial delay of 5 seconds

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

Schedule a task to run everyday at 3 AM

new Timer().Schedule(DoSomething, Timer.GetFutureTime(3), Timer.MILLISECONDS_IN_A_DAY);
查看更多
Deceive 欺骗
3楼-- · 2019-05-01 10:32

You can use javax.swing.Timer. It has delay in constructor:

Timer timer = new Timer(DELAY_IN_MILLISECONDS_INT, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //some code here
    }
});
查看更多
来,给爷笑一个
4楼-- · 2019-05-01 10:46

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:

TimerTask task = new RunMeTask();
Timer timer = new Timer();
timer.schedule(task, 1000, 60000);
查看更多
唯我独甜
5楼-- · 2019-05-01 10:53

One way is to use the ExecutorService:

Runnable task = new Runnable() {    
    @Override
    public void run() {
    // your code
    }
};
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.Seconds);
查看更多
登录 后发表回答