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);
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);
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
}
});