restart timer fails - java

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

Related

DonutProgressBar value is fluctuating when I set progress value for second time

i have created a donutprogressBar and i am setting the progressbar value and its working fine for the first time but when i set the value for second time than the progressbar gets fluctuating between the first value and the second value , i want the progressbar to be set conatsntant to the second value
here is my code :
strMalePercentage = jsonObject.getJSONObject("male").getString("percentage_manglik_present");
txtPercentage.setText("Manglik Male"+strMalePercentage);
Progress(strMalePercentage);
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_ManglikMatchMale){
linearMale.setVisibility(View.VISIBLE);
linearFemale.setVisibility(View.GONE);
imgMatchGender.setBackgroundResource(R.drawable.ic_male1);
txtPercentage.setText("Manglik Male");
Progress(strMalePercentage);
btnMale.setBackgroundColor(getResources().getColor(R.color.textPrimary));
btnMale.setBorderColor(getResources().getColor(R.color.sky_blue));
btnFemale.setBackgroundColor(getResources().getColor(R.color.light_pink));
btnFemale.setTextColor(R.color.textPrimary);
btnMale.setTextColor(R.color.gray_light);
}else
{ linearMale.setVisibility(View.GONE);
linearFemale.setVisibility(View.VISIBLE);
imgMatchGender.setBackgroundResource(R.drawable.ic_female1);
txtPercentage.setText("Manglik Female ");
Progress(strFemalePercentage);
btnFemale.setBackgroundColor(getResources().getColor(R.color.textPrimary));
btnFemale.setBorderColor(getResources().getColor(R.color.light_pink));
btnMale.setBackgroundColor(getResources().getColor(R.color.sky_blue));
btnMale.setTextColor(R.color.textPrimary);
btnFemale.setTextColor(R.color.gray_light);
}
}
public void Progress(final String Percentage){
Timer timer;
donutProgress = (DonutProgress) findViewById(R.id.donut_progress_male);
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
double d = Double.parseDouble(Percentage);
int i = (int) d;
donutProgress.setProgress(0);
donutProgress.setProgress(i);
}
});
}
},1000,100);
}
Maybe something like this, so the timer reference is outside and you can cancel it if already running
private Timer timer;
public void progress(final String Percentage){
donutProgress = (DonutProgress) findViewById(R.id.donut_progress_male);
if (timer == null) {
timer = new Timer();
} else {
timer.cancel();
}
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
double d = Double.parseDouble(Percentage);
int i = (int) d;
donutProgress.setProgress(0);
donutProgress.setProgress(i);
}
});
}
},1000,100);
}

Timertask for sleep

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

Refactoring Java code

Can someone explain me how to refactor the below code. Basically i have a timer functionality which i am using repeatedly. So i want to put that timer into a generic function.
import java.util.Timer;
import java.util.TimerTask;
public class App {
private volatile boolean a = false;
private volatile boolean b = false;
private volatile boolean c = false;
public static void main(String[] args) {
App app = new App();
app.m1();
}
private void m1() {
// m2() should not take more than specified time in timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if(a){
System.out.println("m1 Do nothing");
}
else{
System.out.println("m1 Timeout exception");
}
}
}, 2*60*1000);
a=m2();
System.out.println("Blah");
}
private boolean m2() {
// Killing some time with sleep
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//m3() should not take more than specified time in timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if(b){
System.out.println("m2 Do nothing");
}
else{
System.out.println("m2 Timeout exception");
}
}
}, 1*60*1000);
b = m3();
System.out.println("Blah Blah");
return true;
}
private boolean m3() {
//m4() should not take more than specified time in timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if(c){
System.out.println("m3 Do nothing");
}
else{
System.out.println("m3 Timeout exception");
}
}
}, 20000);
c=m4();
System.out.println("Blah Blah Blah");
return true;
}
private boolean m4() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
Thank you for your help. I am not looking for code help. Want to know your thoughts on minimizing the code.

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

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