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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With