How to make an action in batch mode in java?

Is there a way to create a loop that will execute a task every 3 seconds without using the sleep function

For instance,

try { while (true) { System.out.println(new Date()); Thread.sleep(5 * 1000); } } catch (InterruptedException e) { e.printStackTrace(); } 

But the problem with using the sleep function is that it just freezes the program.

The main idea of โ€‹โ€‹this cycle is to get synchronization with the mysql database (Online).

+4
source share
3 answers

Use java.util.TimerTask

 java.util.Timer t = new java.util.Timer(); t.schedule(new TimerTask() { @Override public void run() { System.out.println("This will run every 5 seconds"); } }, 5000, 5000); 

If you are using a graphical interface, you can use javax.swing.Timer , example:

 int delay = 5000; //milliseconds ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("This will run every 5 seconds"); } }; new javax.swing.Timer(delay, taskPerformer).start(); 

Some information about the difference between java.util.Timer and java.swing.Timer : http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

Both and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. javax.swing.Timer has two functions that can make it a bit easier to use with graphical interfaces. Firstly, its metaphor for event processing is familiar with the graphical interface of programmers and can deal with a dispatching event stream a bit easier. Secondly, automatic thread separation means that you do not have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread that is used to make the cursors blink, tool tips, etc.

+6
source

You can use one of the ScheduledExecutorService implementations if you are ready to move the logic that you want to execute multiple times inside the stream.

Here is an example from the link:

  import static java.util.concurrent.TimeUnit.*; class BeeperControl { private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public void beepForAnHour() { final Runnable beeper = new Runnable() { public void run() { System.out.println("beep"); } }; final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); scheduler.schedule(new Runnable() { public void run() { beeperHandle.cancel(true); } }, 60 * 60, SECONDS); } } 
+4
source

Are you using some kind of user interface?

Java has at least two timers;

Who should be able to achieve the desired

There are also third-party libraries that can also help.

+2
source

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


All Articles