Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Timer in C# in Java?

Tags:

java

c#

timer

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.

like image 838
zbz.lvlv Avatar asked May 16 '14 12:05

zbz.lvlv


2 Answers

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);
like image 188
Erik Pragt Avatar answered Sep 28 '22 15:09

Erik Pragt


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);
like image 37
Alexander_Winter Avatar answered Sep 28 '22 14:09

Alexander_Winter