Timer in java examples

How to set a Timer in Java?

How to set a Timer, say for 2 minutes, to try to connect to a Database then throw exception if there is any issue in connection?

Coul the OP clarify if they desire to simple attempt the action for at least 2 minutes, or if the exception must be thrown now later the two minutes, even if an attempt to connect is currently under way

5 Answers 5

So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I’ve extended the answer to address that.

Setting a timer

First you need to create a Timer (I’m using the java.util version here):

To run the task once you would do:

timer.schedule(new TimerTask() < @Override public void run() < // Your database code here >>, 2*60*1000); // Since Java-8 timer.schedule(() -> /* your database code here */, 2*60*1000); 

To have the task repeat after the duration you would do:

timer.scheduleAtFixedRate(new TimerTask() < @Override public void run() < // Your database code here >>, 2*60*1000, 2*60*1000); // Since Java-8 timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000); 

Making a task timeout

To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:

ExecutorService service = Executors.newSingleThreadExecutor(); try < Runnable r = new Runnable() < @Override public void run() < // Database task >>; Future f = service.submit(r); f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes > catch (final InterruptedException e) < // The thread was interrupted during sleep, wait or join >catch (final TimeoutException e) < // Took too long! >catch (final ExecutionException e) < // An exception from within the Runnable task >finally

This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.

One issue is that although you’ll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.

Источник

Class Timer

Fires one or more ActionEvent s at specified intervals. An example use is an animation object that uses a Timer as the trigger for drawing its frames.

Setting up a timer involves creating a Timer object, registering one or more action listeners on it, and starting the timer using the start method. For example, the following code creates and starts a timer that fires an action event once per second (as specified by the first argument to the Timer constructor). The second argument to the Timer constructor specifies a listener to receive the timer’s action events.

int delay = 1000; //milliseconds ActionListener taskPerformer = new ActionListener() < public void actionPerformed(ActionEvent evt) < //. Perform a task. > >; new Timer(delay, taskPerformer).start();

Timers are constructed by specifying both a delay parameter and an ActionListener . The delay parameter is used to set both the initial delay and the delay between event firing, in milliseconds. Once the timer has been started, it waits for the initial delay before firing its first ActionEvent to registered listeners. After this first event, it continues to fire events every time the between-event delay has elapsed, until it is stopped.

After construction, the initial delay and the between-event delay can be changed independently, and additional ActionListeners may be added.

If you want the timer to fire only the first time and then stop, invoke setRepeats(false) on the timer.

Although all Timer s perform their waiting using a single, shared thread (created by the first Timer object that executes), the action event handlers for Timer s execute on another thread — the event-dispatching thread. This means that the action handlers for Timer s can safely perform operations on Swing components. However, it also means that the handlers must execute quickly to keep the GUI responsive.

In v 1.3, another Timer class was added to the Java platform: java.util.Timer . Both it and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don’t have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.

You can find further documentation and several examples of using timers by visiting How to Use Timers, a section in The Java Tutorial.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans has been added to the java.beans package. Please see XMLEncoder .

Источник

Class Timer

Fires one or more ActionEvent s at specified intervals. An example use is an animation object that uses a Timer as the trigger for drawing its frames.

Setting up a timer involves creating a Timer object, registering one or more action listeners on it, and starting the timer using the start method. For example, the following code creates and starts a timer that fires an action event once per second (as specified by the first argument to the Timer constructor). The second argument to the Timer constructor specifies a listener to receive the timer’s action events.

int delay = 1000; //milliseconds ActionListener taskPerformer = new ActionListener() < public void actionPerformed(ActionEvent evt) < //. Perform a task. > >; new Timer(delay, taskPerformer).start();

Timers are constructed by specifying both a delay parameter and an ActionListener . The delay parameter is used to set both the initial delay and the delay between event firing, in milliseconds. Once the timer has been started, it waits for the initial delay before firing its first ActionEvent to registered listeners. After this first event, it continues to fire events every time the between-event delay has elapsed, until it is stopped.

After construction, the initial delay and the between-event delay can be changed independently, and additional ActionListeners may be added.

If you want the timer to fire only the first time and then stop, invoke setRepeats(false) on the timer.

Although all Timer s perform their waiting using a single, shared thread (created by the first Timer object that executes), the action event handlers for Timer s execute on another thread — the event-dispatching thread. This means that the action handlers for Timer s can safely perform operations on Swing components. However, it also means that the handlers must execute quickly to keep the GUI responsive.

In v 1.3, another Timer class was added to the Java platform: java.util.Timer . Both it and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don’t have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.

You can find further documentation and several examples of using timers by visiting How to Use Timers, a section in The Java Tutorial.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans has been added to the java.beans package. Please see XMLEncoder .

Источник

How to Use Swing Timers

A Swing timer (an instance of javax.swing.Timer ) fires one or more action events after a specified delay. Do not confuse Swing timers with the general-purpose timer facility in the java.util package. This page describes only Swing timers.

In general, we recommend using Swing timers rather than general-purpose timers for GUI-related tasks because Swing timers all share the same, pre-existing timer thread and the GUI-related task automatically executes on the event-dispatch thread. However, you might use a general-purpose timer if you don’t plan on touching the GUI from the timer, or need to perform lengthy processing.

You can use Swing timers in two ways:

  • To perform a task once, after a delay.
    For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.
  • To perform a task repeatedly.
    For example, you might perform animation or update a component that displays progress toward a goal.

Swing timers are very easy to use. When you create the timer, you specify an action listener to be notified when the timer «goes off». The actionPerformed method in this listener should contain the code for whatever task you need to be performed. When you create the timer, you also specify the number of milliseconds between timer firings. If you want the timer to go off only once, you can invoke setRepeats(false) on the timer. To start the timer, call its start method. To suspend it, call stop .

Note that the Swing timer’s task is performed in the event dispatch thread. This means that the task can safely manipulate components, but it also means that the task should execute quickly. If the task might take a while to execute, then consider using a SwingWorker instead of or in addition to the timer. See Concurrency in Swing for instructions about using the SwingWorker class and information on using Swing components in multi-threaded programs.

Let’s look at an example of using a timer to periodically update a component. The TumbleItem applet uses a timer to update its display at regular intervals. (To see this applet running, go to How to Make Applets. This applet begins by creating and starting a timer:

timer = new Timer(speed, this); timer.setInitialDelay(pause); timer.start();

The speed and pause variables represent applet parameters; as configured on the other page, these are 100 and 1900 respectively, so that the first timer event will occur in approximately 1.9 seconds, and recur every 0.1 seconds. By specifying this as the second argument to the Timer constructor, TumbleItem specifies that it is the action listener for timer events.

After starting the timer, TumbleItem begins loading a series of images in a background thread. Meanwhile, the timer events begin to occur, causing the actionPerformed method to execute:

public void actionPerformed(ActionEvent e) < //If still loading, can't animate. if (!worker.isDone()) < return; >loopslot++; if (loopslot >= nimgs) < loopslot = 0; off += offset; if (off < 0) < off = width - maxWidth; >else if (off + maxWidth > width) < off = 0; >> animator.repaint(); if (loopslot == nimgs - 1) < timer.restart(); >>

Until the images are loaded, worker.isDone returns false , so timer events are effectively ignored. The first part of the event handling code simply sets values that are employed in the animation control’s paintComponent method: loopslot (the index of the next graphic in the animation) and off (the horizontal offset of the next graphic).

Eventually, loopslot will reach the end of the image array and start over. When this happens, the code at the end of actionPerformed restarts the timer. Doing this causes a short delay before the animation sequence begins again.

Источник

Читайте также:  Сумма двух чисел питон программа
Оцените статью