How to stop a running TimerTask - java

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();
}
}
}

Related

Can Java print text (letter by letter) into the command prompt?

Timer timer = new Timer();
TimerTask task = new TimerTask(){
int letter = 0;
#Override
public void run() {
if(letter<StatementInput.length()){
System.out.print(StatementInput.charAt(letter));
letter++;
}else{timer.cancel();}
}
};
timer.scheduleAtFixedRate(task,0,100 );
}
I'm trying to print out text one character at a time, with a small interval between each letter. When I try Thread.sleep or the above code, it won't print smoothly, the text comes out in bunches. Is there any way for me to smoothen it out?
I am running the code in intellij and am new to Java.
EDIT: Here's the full source code:
import java.util.Timer;
import java.util.TimerTask;
public class test {
public static void statement(String StatementInput) throws InterruptedException {
Timer timer = new Timer();
TimerTask task = new TimerTask(){
int letter = 0;
#Override
public void run() {
if(letter<StatementInput.length()){
System.out.print(StatementInput.charAt(letter));
letter++;
}else{timer.cancel();}
System.out.flush();
}
};
timer.scheduleAtFixedRate(task,0,100 );
}
public static void main(String[] args) throws InterruptedException {
test.statement("Hello World!!!!");
}
}

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 stop a timer with an if statement

I'm trying to stop a timer that ticks down from ten seconds to zero.
The problem is that the finish method only returns the first tick, rather than counting all the numbers down to one.
How can I make a boolean method return a value for every second rather than just the first?
import java.util.Timer;
import java.util.TimerTask;
public class Countdown {
static int interval;
static Timer timer;
boolean off;
public Countdown() {
int seconds = 10;
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = seconds;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private int setInterval() {
off = false;
if (interval == 1){
timer.cancel();
off = true;
return --interval;
}else{
off = false;
return --interval;
}
}
public boolean finish(){
return off;
}
}
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public static void main(String[] args){
Countdown countDown = new Countdown();
countDown.finish()
System.out.println(countDown.finish);
if(countDown.finish() == true){
System.out.println("works");
}
}
If you want to write the value of finish every second, you should design your code to print it ever second, not just on startup...
ATM finish is only printed in the main-method and nowhere else. Move that line into the Runnable used by the Timer and it should print as expected.

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

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);

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
}

Categories