Timer and TimerTask - how to reschedule Timer from within TimerTask run - java

basically what I want to do is to make a Timer that runs a specific TimerTask after x seconds, but then the TimerTask can reschedule the Timer to do the task after y seconds. Example is below, it gives me an error "Exception in thread "Timer-0" java.lang.IllegalStateException: Task already scheduled or cancelled" on line where I try to schedule this task in TimerTask run.
import java.util.Timer;
import java.util.TimerTask;
public class JavaReminder {
public JavaReminder(int seconds) {
Timer timer = new Timer();
timer.schedule(new RemindTask(timer, seconds), seconds*2000);
}
class RemindTask extends TimerTask {
Timer timer;
int seconds;
RemindTask(Timer currentTimer, int sec){
timer = currentTimer;
seconds = sec;
}
#Override
public void run() {
System.out.println("ReminderTask is completed by Java timer");
timer = new Timer();
timer.schedule(this, seconds*200);
System.out.println("scheduled");
}
}
public static void main(String args[]) {
System.out.println("Java timer is about to start");
JavaReminder reminderBeep = new JavaReminder(2);
System.out.println("Remindertask is scheduled with Java timer.");
}
}

Use new RemindTask instead of existing one.
It should be
timer.schedule(new RemindTask(timer, seconds), seconds*200);
instead of
timer.schedule(this, seconds*200);

Related

Java TimerTask in While Loop [duplicate]

I am using java.util.Timer class and I am using its schedule method to perform some task, but after executing it for 6 times I have to stop its task.
How should I do that?
Keep a reference to the timer somewhere, and use:
timer.cancel();
timer.purge();
to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.
private static int count = 0;
public static void run() {
count++;
if (count >= 6) {
timer.cancel();
timer.purge();
return;
}
... perform task here ....
}
Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.
You should stop the task that you have scheduled on the timer:
Your timer:
Timer t = new Timer();
TimerTask tt = new TimerTask() {
#Override
public void run() {
//do something
};
};
t.schedule(tt,1000,1000);
In order to stop:
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
Notice that just cancelling the timer will not terminate ongoing timertasks.
Terminate the Timer once after awake at a specific time in milliseconds.
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);

Java - Reusing Timer Object after calling cancel

I have an application in Java where I need to schedule a TimerTaskwhich will be executed after 500ms , however if a certain event occurs, I must reset the timer for this task (so that we must wait another 500ms for it to execute). I have a timer declared for the whole class. I use the following code:
public static void main(String[] args) {
if (curr_pck == my_pck) {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myTask();
}
}, 500);
}
}
public static void myTask() {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myTask();
}
}, 500);
//EXECUTE CODE WHICH ISN'T RELEVANT TO THE QUESTION
}
I know that if I use timer.cancel() I can't reuse the timer object, however I thought reinitialising it in the line timer = new Timer() should solve this issue. Is there any way around this?
EXCEPTION on line timer.schedule(new TimerTask() { inside myTask() function:
java.lang.IllegalStateException: Timer already cancelled.
Create a class Timerr with the appropriate methods. Then access it as if it were a normal timer.
public class Timerr
{
private Timer timer;
public Timerr()
{
timer = new Timer();
start();
}
public void start()
{
timer.schedule(new TimerTask()
{
#Override
public void run()
{
System.out.println("hi");
}
}, 500);
}
public void reset()
{
timer.cancel();
timer.purge();
start();
}
}
Create instance
private Timerr timer = new Timerr();
Do your reset
if(condition)
{
timerr.reset();
}
You may want to check out Java's Swing timer. It works somewhat differently and you may have to write an internal class or an actionlistener, but the Swing timer includes .stop() and .restart(), which seem like they would work better in your application.

How to display seconds of the timer in the output screen?

import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
public class Java {
Toolkit toolkit;
Timer timer;
int t=10000,total;
public Java(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
total =seconds * t;
System.out.println(total);
timer.schedule(new RemindTask(), total);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
System.exit(0);
}
}
public static void main(String args[]) {
new Java(5);
System.out.println("Timer started");
}
}
How can I display the seconds similar to countdown timer in output screen, I want to use it in a quiz program
0:53 => 0:52 like this ...
What you can do is schedule a task at a fixed rate (Timer.scheduleAtFixedRate) using a period of 1 second. As far as possible, we should refrain from calling the System.exit(0) and wait for the threads to complete their tasks. We can make the main thread (the thread that started the timer) sleep for the duration of the timer tasks and then when it finally wakes up, it cancels the timer:
private final Timer timer;
public CountDownTimer(int seconds) {
timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(seconds), 0, 1000);
}
class RemindTask extends TimerTask {
private volatile int remainingTimeInSeconds;
public RemindTask(int remainingTimeInSeconds) {
this.remainingTimeInSeconds = remainingTimeInSeconds;
}
public void run() {
if (remainingTimeInSeconds != 0) {
System.out.println(remainingTimeInSeconds + " ...");
remainingTimeInSeconds -= 1;
}
}
}
public static void main(String args[]) throws InterruptedException {
CountDownTimer t = new CountDownTimer(5);
System.out.println("Timer started");
Thread.sleep(5000);
t.end();
}
private void end() {
this.timer.cancel();
}

How to use Timer

I have an application made in Netbeans and I don't have any idea how to use a Timer in Java. In Winform there's a control box of Timer which is drag and use only. Now I want to use a timer for 1 seconds after about.setIcon(about4); (which is GIF) is executed.
import javax.swing.ImageIcon;
int a2 = 0, a3 = 1, a4 = 2;
ImageIcon about2 = new ImageIcon(getClass().getResource("/2What-is-the-Game.gif"));
about2.getImage().flush();
ImageIcon about3 = new ImageIcon(getClass().getResource("/3How-to-play.gif"));
about3.getImage().flush();
ImageIcon about4 = new ImageIcon(getClass().getResource("/4About-end.gif"));
about4.getImage().flush();
if(a2 == 0)
{
a2=1;
a3=1;
about.setIcon(about2);
}
else if (a3 == 1)
{
a3=0;
a4=1;
about.setIcon(about3);
}
else if (a4 == 1)
{
a4=0;
a2=0;
about.setIcon(about4);
}
}
How can I achieve this?
In Java, we have several ways of Timer implementation or rather its uses, a few of them are-
To set up a specific amount of delay until a task is executed.
To find the time difference between two specific events.
Timer class provides facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
public class JavaReminder {
Timer timer;
public JavaReminder(int seconds) {
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new RemindTask(), seconds*1000); //delay in milliseconds
}
class RemindTask extends TimerTask {
#Override
public void run() {
System.out.println("ReminderTask is completed by Java timer");
timer.cancel(); //Not necessary because we call System.exit
//System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("Java timer is about to start");
JavaReminder reminderBeep = new JavaReminder(5);
System.out.println("Remindertask is scheduled with Java timer.");
}
}
Read more from here:
http://javarevisited.blogspot.in/2013/02/what-is-timer-and-timertask-in-java-example-tutorial.html
http://www.javatutorialhub.com/timers-java
Declare an instance of java.util.Timer in your code (in the constructor?) and configure/control it with the methods found in the docs.
import java.util.Timer;
import java.util.TimerTask;
...
private Timer t;
public class MyClass()
{
t=new Timer(new TimerTask(){
#Override
public void run()
{
//Code to run when timer ticks.
}
},1000);//Run in 1000ms
}

How to stop a running TimerTask

I am trying to make a simple timer that plays a beep after the specified number of seconds. I managed to get it to work, but the TimerTask continues to run after the beep. Now do I stop execution?
Here is my code:
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;
class Alarm {
public static void main(String[] args) {
long delay;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a delay in seconds: ");
delay = scan.nextInt()*1000;
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
Toolkit.getDefaultToolkit().beep();
}
};
timer.schedule(task, delay);
}
}
You need to cancel the timer by calling the following methods
timer.cancel(); // Terminates this timer, discarding any currently scheduled tasks.
timer.purge(); // Removes all cancelled tasks from this timer's task queue.
This will cancel the task, so something like this would work:
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;
class Alarm {
private static boolean run = true;
public static void main(String[] args) {
long delay;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a delay in seconds: ");
delay = scan.nextInt()*1000;
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
#Override
public void run() {
if(run) {
Toolkit.getDefaultToolkit().beep();
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, delay);
// set run to false here to stop the timer.
run = false;
}
}
Here is what worked for me (used the purge() suggestion also):
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;
class Alarm {
public static void main(String[] args) {
long delay;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a delay in seconds: ");
delay = scan.nextInt()*1000;
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
#Override
public void run() {
Toolkit.getDefaultToolkit().beep();
timer.cancel();
timer.purge();
}
};
timer.schedule(task, delay);
}
}
cancel() should do it - cancel stops the cancels the given TimerTask / Timer
isStart = true; // if true timmer function countiue called , else time canceled
Timer timer = new Timer();
timer.schedule(new TimerClass(), 0, 5000);
class TimerClass extends TimerTask {
public void run() {
if (isStart) {
yourFunction();
}else {
cancel();
}
}
}

Categories