Timertask for sleep - java

I want to use TimerTask for Sleep, but I am unable to run this code.
The run function is called for the first time, and then it waits infinitely. Is there any issue with my code?
import java.util.Timer;
import java.util.TimerTask;
public class TimeExecutor {
class LocalSleep extends TimerTask {
private int noOfSeconds;
private int count = 0;
private Timer timer;
public LocalSleep(int noOfSeconds, Timer timer) {
this.noOfSeconds = noOfSeconds;
this.timer = timer;
}
void sleeeep() {
if (count < noOfSeconds) {
System.out.println("Count: " + count);
count++;
} else
timer.cancel();
}
#Override
public void run() {
sleeeep();
}
}
public static void main(String args[]) {
Timer timer = new Timer();
TimeExecutor t = new TimeExecutor();
timer.schedule(t.new LocalSleep(5, timer), 1000);
}
}

Working after replacing
timer.schedule(t.new LocalSleep(5, timer), 1000);
with:
timer.schedule(t.new LocalSleep(5, timer), 0, 1000);

Related

How can create timer with JLabel?

I want to display in my JPanel a JLabel with timer in this mode, for example:
03:50 sec
03:49 sec
....
....
00:00 sec
So I have build this code:
#SuppressWarnings("serial")
class TimeRefreshRace extends JLabel implements Runnable {
private boolean isAlive = false;
public void start() {
Thread t = new Thread(this);
isAlive = true;
t.start();
}
public void run() {
int timeInSecond = 185
int minutes = timeInSecond/60;
while (isAlive) {
try {
//TODO
} catch (InterruptedException e) {
log.logStackTrace(e);
}
}
}
}//fine autoclass
And with this code, I can start the JLabel
TimeRefreshRace arLabel = new TimeRefreshRace ();
arLabel.start();
So I have the time in secondo for example 180 second, how can I create the timer?
Here is an example, how to build a countdown label. You can use this pattern to create your component.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class TimerTest {
public static void main(String[] args) {
final JFrame frm = new JFrame("Countdown");
final JLabel countdownLabel = new JLabel("03:00");
final Timer t = new Timer(1000, new ActionListener() {
int time = 180;
#Override
public void actionPerformed(ActionEvent e) {
time--;
countdownLabel.setText(format(time / 60) + ":" + format(time % 60));
if (time == 0) {
final Timer timer = (Timer) e.getSource();
timer.stop();
}
}
});
frm.add(countdownLabel);
t.start();
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
}
private static String format(int i) {
String result = String.valueOf(i);
if (result.length() == 1) {
result = "0" + result;
}
return result;
}
}
You could within your try block call the Event Dispatcher Thread (EDT) and update your UI:
try {
SwingUtils.invokeLater(new Runnable() {
#Override
public void run() {
this.setText(minutes + " left");
}
}
//You could optionally block your thread to update your label every second.
}
Optionally, you could use a Timer instead of an actual thread, so your TimerRefreshRace will have its own timer which periodically fires an event. You would then use the same code within your try-catch block to update the UI.

How to use Java.Util.Timer

I want to make a simple program that counts seconds up until 100 using Java.Util.Timer
The code below is the code I am using, however it simply prints all the numbers out at once without waiting a second between each one. How would I fix that? (Ordinarily I would use a thread.sleep but this is just proof of concept.)
import java.util.Timer;
import java.util.TimerTask;
public class Main {
static Timer timer = new Timer();
static int seconds = 0;
public static void main(String[] agrs) {
MyTimer();
}
public static void MyTimer() {
TimerTask task;
task = new TimerTask() {
#Override
public void run() {
while (seconds < 100) {
System.out.println("Seconds = " + seconds);
seconds++;
}
}
};
timer.schedule(task, 0, 1000);
}
}}
Don't use this while loop:
task = new TimerTask() {
#Override
public void run() {
while (seconds < 100) {
System.out.println("Seconds = " + seconds);
seconds++;
}
}
};
The while loop will run immediately as there's no delay inside of it. Instead you want to Timer itself to be your loop, meaning there's no need for this loop.
Instead use an if block to check if the count is < some max number and if so, print it out and increment the count.
task = new TimerTask() {
private final int MAX_SECONDS = 100;
#Override
public void run() {
if (seconds < MAX_SECONDS) {
System.out.println("Seconds = " + seconds);
seconds++;
} else {
// stop the timer
cancel();
}
}
};
In order to stop the timer the timer.cancel() should be invoked (not only the one of the TimerTask), so the timer is stopped and in cascade the other related threads.
#Override
public void run() {
if (seconds < Orologio.MAX_SECONDS) {
System.out.println("Seconds = " + seconds);
seconds++;
} else {
timer.cancel();
System.out.println("Timer canceled");
}
}
};

how to return null to int method

iam new to programming.iam wrking on a quiz game software. here i want a count down to be printed as "3,2,1,go...go...go"
package t2;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = 3;
System.out.println("3");
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval() {
String go="go...go...go";
if (interval == 2)
{
timer.cancel();
return go;
}
return --interval;
}
}
this says that setInterval() has int as return value.if i place System.out.print("go");
in the place of return go; it prints go and prints 1 which is out of requirement. please any buddy can tell me how to do this.
One option would be to change your setInterval() method to return a string like such:
private static final String setInterval() {
String go="go...go...go";
if (interval == 2)
{
timer.cancel();
return go;
}
--interval;
return String.valueOf(interval);
}
Change the return type of setInterval to object to take advantage of the overloaded println method and the conditional should check for 1 instead of 2. Also use print instead of println to have the output on the same line.
private static final Object setInterval() {
String go="go...go...go";
if (interval == 1)
{
timer.cancel();
return go;
}
return --interval;
}
Full Example
package t2;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = 3;
System.out.print("3,");
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.print(setInterval() + ",");
}
}, delay, period);
}
private static final Object setInterval() {
String go = "go...go...go";
if (interval == 1) {
timer.cancel();
return go;
}
return --interval;
}
}

restart timer fails

I would like to restart my timer when I receive a KeepAlive, the problem is that sometimes it doesn't restart, instead of that it creates a new one, so, finally the timer reaches the limit:
public class KeepAliveTimer {
long macAddress;
Timer timer;
String ip;
public KeepAliveTimer(long mac, String ipAddress){
this.macAddress = mac;
this.ip = ipAddress;
timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
timerFinished();
}
};
timer.schedule(timerTask, 10*60*1000);
}
public void update() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
timerFinished();
}
};
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(timerTask, 10*60*1000);
}
public void timerFinished() {
//tasks
}
}
The object KeepAliveTimer is created when received the first keepAlive and updated by following ones
You should not cancel the whole timer, but only the TimerTask. This is how I'd write your code:
public class KeepAliveTimer {
final Timer timer = new Timer();
final long macAddress;
final String ip;
volatile TimerTask timerTask;
public KeepAliveTimer(long mac, String ipAddress) {
this.macAddress = mac;
this.ip = ipAddress;
}
public void update() {
if (timerTask != null) timerTask.cancel();
timer.schedule(timerTask(), 10 * 60 * 1000);
}
private TimerTask timerTask() {
return timerTask = new TimerTask() {
#Override public void run() { timerFinished(); }
};
}
public void timerFinished() {
// tasks
}
}
Note that I don't duplicate the scheduling inside the constructor. You should initialize with
new KeepAliveTimer(mac, ip).update();

java swing timer not going off

I can't seem to get this timer to go off. the program compiles and from my understanding this should ping every 1000ms or 1 second and perform the lines in the actionPerformed{} function.
public void stringGeneration(String args[]){
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String fullIstring = java.lang.String.valueOf(injectString[0] + injectString[1] + injectString[2] + injectString[3] + injectString[4]);
jLabel3.setText(fullIstring);
System.out.println("output");
}
};
Timer timer = new Timer(1000, taskPerformer);
timer.setRepeats(true);
timer.start();
//Thread.sleep(500);
}
i just gave you an example and not something to copy paste. But you can try this if you want to try as is. In your case the above example should look like:
class HeartBeatTask extends TimerTask {
private int timerInterval;
public HeartBeatTask(int timeInterval)
{
this.timerInterval = timeInterval;
}
public void run()
{
String fullIstring = java.lang.String.valueOf(injectString[0] + injectString[1] + injectString[2] + injectString[3] + injectString[4]);
jLabel3.setText(fullIstring);
System.out.println("output");
}
}
Your method will then call the above class like this:
public void stringGeneration(String args[]){
HeartBeatTask tt = new HeartBeatTask();
t1.schedule(tt, 0, 1000 * 60 * 2);
}
This is how i would to a scheduled task in java:
import java.util.TimerTask;
class HeartBeatTask extends TimerTask
{
private int timerInterval;
public HeartBeatTask(int timeInterval)
{
this.timerInterval = timeInterval;
}
public void run()
{
// Your function call to schedule here
}
public static void main(String[] args)
{
java.util.Timer t1 = new java.util.Timer();
HeartBeatTask tt = new HeartBeatTask();
t1.schedule(tt, 0, 1000 * 60 * 2);
}
}
Hope that helps

Categories