Equivalent timer in C # in Java?

In C #, a timer fires an event at a specific interval when it is turned on. How to achieve this in Java?

I want the method to run at a specific interval. I know how to do this in C #, but not in Java.

Code in C #:

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

I tried Timerand TimerTaskbut I'm not sure if this method will work when other methods are started.

+4
source share
4 answers

You look at the classes you need. Timer and TimerTask are correct, and they will work in the background if you use them something like this:

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

- ExecutorService:

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

You can use the codeplex library to implement this.

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

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

Schedule a task for daily work at 3 a.m.

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

You can use javax.swing.Timer . It has delayin the constructor:

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

Source: https://habr.com/ru/post/1540833/


All Articles