How to run a timer? - java

I want to run a timer which says time is expired after 30 seconds,how can do so?
Some task to be run only for some seconds then showing expired, how can i do so?

I'd recommend using ScheduledExecutorService from the java.util.concurrent package, which has a richer API than other Timer implementations within the JDK.
// Create timer service with a single thread.
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
// Schedule a one-off task to run in 10 seconds time.
// It is also possible to schedule a repeating task.
timer.schedule(new Callable<Void>() {
public Void call() {
System.err.println("Expired!");
// Return a value here. If we know we don't require a return value
// we could submit a Runnable instead of a Callable to the service.
return null;
}
}, 10L, TimeUnit.SECONDS);

The actionPerformed method is called after 30 sec
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class TimerExample {
public static void main(String args[]) {
new JFrame().setVisible( true );
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println( "expired" );
}
};
Timer timer = new Timer( 30000, actionListener );
timer.start();
}
}

Use Timer.

Related

Set timer for executing task multiple times

I have a requirement, where I need to create a timer task which will execute the function after every 10 sec. There is reset Button, on click of that reset Button I want to reset my time from 10 sec to 30 sec. Now after 30 sec when it execute the function I need to reset my timer again to 10 sec. I tried using Handler , TimerTask and CountDownTimer, but not able to achieve the requirement. Can anyone suggest me the best way of solving this problem
// OnCreate of Activity
if (timerInstance == null) {
timerInstance = Timer()
timerInstance?.schedule(createTimerTask(), 10000L, 10000L)
}
private fun createTimerTask(): TimerTask {
return object : TimerTask() {
override fun run() {
Log.d("TimerTask", "Executed")
//presenter?.onCountdownTimerFinished(adapter.activeCallList, adapter.previousPosition)
}
}
}
//On Reset Button Click
timerInstance?.cancel()
timerInstance = Timer()
timerInstance?.schedule(createTimerTask(), 30000L, 30000L)
When your button is pressed, you could cancel the submitted TimerTask and reschedule with a delay of 30sec and a period of 10sec ?
https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html#scheduleAtFixedRate-java.util.TimerTask-long-long-
Cancel the first submitted task by calling .cancel on it.
use 30000L, 10000L as delay and period on the schedule in the button
Example code :
package so20190423;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
public static void main(String[] args) {
System.out.println(new Date());
Timer timer = new Timer();
TimerTask task = newTask();
timer.scheduleAtFixedRate(task, 10000L, 10000L);
task.cancel();
timer.scheduleAtFixedRate( newTask(), 30000L, 10000L);
}
protected static TimerTask newTask() {
return new TimerTask() {
#Override
public void run() {
System.out.println("YO");
System.out.println(new Date());
}
};
}
}
HTH!

Java timer wont run

So i want to print out a word every second for 10 seconds, but nothing is working
Here's my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class Main{
public static void main (String[] args){
class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("helo");
}
}
ActionListener dummy = new TimerListener();
Timer power_up_time = new Timer(10000,dummy);
power_up_time.addActionListener(dummy);
power_up_time.start();
}
}
EDIT: so i added the start function and it still doesnt work
I believe that you need to start a Timer in order to make it work.
Something like this:
Timer timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
timer.start();
In newer versions of Java (from the last ten years or so) I would suggest using a ScehduledExecutorService
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(() -> System.out.println("hello"), 0, 1, TimeUnit.SECONDS);
TimeUnit.SECONDS.sleep(10);
ses.shutdown();
If the code you posted is complete you are starting the timer right before the application (i.e. the main thread) terminates. Thus the scheduler won't run long enough to execute the timer.
Try sleeping or running in a loop with some exit condition (that's probably what you'll want to do anyways).
You do not initialize and start the Swing toolkit, hence your application immediately terminates.
If you really want to use the Swing Timer, you need to show at least some window or dialog, so that the Swing event thread is running, e.g. by adding the following to the end of your main() method:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JFrame("Frame title").setVisible(true);
}
});
See the other answers for alternatives outside of Swing.

I am trying to use javax.swing.timer . The code in actionperformed method is not running. May be the timer is not starting. What is the fault?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class TimeController {
public static void main(String arg[]){
TimeController m = new TimeController();
System.out.println("starting");
m.start();
}
Timer timer = new Timer (1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("Running");
}
});
public void start(){
timer.start();
}
}
I think there is no fault at all.
The Timer starts its task in the background
Your application terminates before the first execution of the Timers method takes place.
For testing you could add
try {
Thread.sleep(5000);
} catch(Exception e){
// Add exception handling
}
right after `m.start();
For some reason the Timer needs to fire at least once to prevent the program from termination. After it fires once, it does hold the program running, even after the main method terminates.
Probably the bug got unnoticed as this is a rather unusual work flow. Delay the termination of the main thread as proposed by #StefanFreitag.

Timer Task Only Runs Once

How do I make my Timer Task run more than once? This is really bothering me..
timer = new Timer();
timer.schedule(new Client(), 1000);
public void run() {
try {
System.out.println("sent data");
socketOut.write(0);
} catch (Exception e) {
// disconnect client on their side
Game.destroyGame();
timer.cancel();
timer.purge();
}
}
I want this timer to run for an infinite amount of time until the Exception occurs.
When the Javadoc says that it repeats with a specific delay, the delay is the initial delay before the TimerTask starts and not for how long the TimerTask will run. You can repeat the task every period milliseconds. Look at the schedule method. Below is a simple example that repeats every 2 seconds, indefinitely. In the example, the call:
timer.schedule(new RemindTask(seconds), 0, seconds * 1000);
tells timer to run the RemindTask every seconds seconds (*1000 because the time here is really in miliseconds), with an initial delay of 0 - i.e. start the RemindTask right away and then keep repeating at regular intervals.
import java.util.Timer;
import java.util.TimerTask;
public class Main {
static Timer timer;
static int i = 0;
class RemindTask extends TimerTask {
private int seconds;
public RemindTask(int seconds) {
this.seconds = seconds;
}
public void run() {
i+= seconds ;
System.out.println(i + " seconds!");
}
}
public Main(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(seconds), 0, seconds * 1000);
}
public static void main(String args[]) {
new Main(2);
System.out.format("Task scheduled.%n");
}
}
Looks like to me you're running a GUI program (I'm assuimg SWING, because your other question you were using SWING). So here's a bit of advice. Use a javax.swing.Timer for Swing program.
"How do I make my Timer Task run more than once? "
javax.swing.Timer has methods .stop() and .start() and .restart(). A basic implementation of the Timer object is something like this
Timer timer = new Timer(delay, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
timer.start();
You can do anything you want in the actionPerformed and it will fire an event every how many ever milliseconds you provide to the delay. You can have a button call .start() or .stop()
See this answer for a simple implementation of Timer imitating a sort of stop watch for a Boggle game

Swing timer not Starting

I am trying to print a statement repeatedly using Swing Timer but the statement doesn't gets printed !
What's the mistake I am making ?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class SwingTimer implements ActionListener {
Timer timer;
public static void main(String[] args) {
SwingTimer obj = new SwingTimer();
obj.create();
}
public void create() {
timer = new Timer(1000, this);
timer.setInitialDelay(0);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello using Timer");
}
}
The javax.swing.Timer probably starts as a daemon thread: it doesn't keep the jvm alive, your main ends, the jvm exits. It post the timer events to the GUI event queue which starts when the first dialog or frame is made visible.
You have to create a JFrame, and make it visible or use the java.util.Timer if you don't need windowing system at all.
The following code shows how to use java.util.Timer:
import java.util.Timer;
import java.util.TimerTask;
public class TimerDemo extends TimerTask {
private long time = System.currentTimeMillis();
#Override public void run() {
long elapsed = System.currentTimeMillis() - time;
System.err.println( elapsed );
time = System.currentTimeMillis();
}
public static void main( String[] args ) throws Exception {
Timer t = new Timer( "My 100 ms Timer", true );
t.schedule( new TimerDemo(), 0, 100 );
Thread.sleep( 1000 ); // wait 1 seconde before terminating
}
}
javax.swing.Timer should only be used when using Swing applications. Currently your main Thread is exiting as the Timer uses a daemon Thread. As a workaround you could do:
public static void main(String[] args) {
SwingTimer obj = new SwingTimer();
obj.create();
JOptionPane.showMessageDialog(null, "Timer Running - Click OK to end");
}
An alternative for non-UI applications is to use ScheduledExecutorService

Categories

Resources