Using a variable inside Timer - java

I'm working on a program that has a prints time only when a function is called. I'm using timer for the continuous adding of seconds.
Timer gameTimer = new Timer ();
TimerTask time = new TimerTask() {
int sec = 0;
public void run()
{
sec++;
}
};
gameTimer.scheduleAtFixedRate(time, 1000, 1000);
However, I cannot use the variable sec outside the run() so I can print it. I tried to place sec outside TimerTask but of course sec++ would not work. Any help? Thanks!

Since only final variables accessible in anonymous class, but with this below hack you can achieve what you want.
final int [] result = new int[1]; // Create a final array
TimerTask time = new TimerTask() {
int sec = 0;
public void run()
{
sec++;
result[0] = sec;
}
};
// Now Print whenver you want it
System.out.println(result[0]);
This way you are not reassigning the array to a new object just changing the content inside it

Just make your own interface extending the original interface.
https://docs.oracle.com/javase/tutorial/java/IandI/nogrow.html
interface CustomTimerTask extends TimerTask {
public int getTicks();
}
CustomTimerTask time = new CustomTimerTask () {
int sec = 0;
#Override
public void run()
{
sec++;
}
#Override
public synchronized int getTicks() {
return sec;
}
};
System.out.println("The time passed is: " + time.getTicks());
Just make sure you make it synchronized because you're working with two threads now.

Related

"local variables referenced from an inner class must be final or effectively final" in MouseEvent

I am trying to get the integer input from a jtextfield and set it as the integer for a timer jlabel when the jbutton is clicked but I keep getting this error inside the MouseEvent method
local variables referenced from an inner class must be final or effectively final
Code:
private void timerStartMouseClicked(java.awt.event.MouseEvent evt) {
int a = Integer.parseInt(timerInput.getText());
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
timeLeft.setText(Integer.toString(a));
--a;
if (a == -1){
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
timer.cancel();
} else if(isRunning){
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
}
}
};
timer.scheduleAtFixedRate(task, 1000, 1000);
}
I am still new with Timer Events and Mouse Events, I tried to declare a as a global var which still gives me the same error unless I declare it a value within the method but I need to get the input from the jtextfield.
Not tested, but I think this will work.
private void timerStartMouseClicked(java.awt.event.MouseEvent evt) {
final int a = Integer.parseInt(timerInput.getText());
Timer timer = new Timer();
TimerTask task = new TimerTask() {
int localCount = a;
public void run() {
timeLeft.setText(Integer.toString(localCount));
--localCount;
if (localCount == -1){
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
timer.cancel();
} else if(isRunning){
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
}
}
};
timer.scheduleAtFixedRate(task, 1000, 1000);
What's going on is that a is a local variable and is going to vanish into the ether when this method ends, therefore it's not safe to use. If the variable is final then it's safe for Java to copy the value of a into your inner class. However you need to modify a so a constant value won't work.
So we just copy the value into a different variable, one inside the inner class. This makes everything work fine, because now the inner class has its own variable to work with.

How to use a for loop to always change the string to another string and to another in an array anytime an if condition is true

I am writing a Java program in which I have an array list of 5 strings and a countdown timer of 5 seconds. My question is this, I want the string to be changing anytime the timer is in 1 second. That is whenever the countdown timer is at 1 second, the string should change to another string then when it gets to 1 second it should change to another string till all the strings in the array list as shown.
Keep a reference to the timer somewhere, and use:
timer.cancel();
timer.purge();
I think this demo code will help you:
class Helper extends TimerTask
{
public static Timer timer;
public static int i = 0;
public static void setTimer(Timer timer) {
Helper.timer = timer;
}
public void run()
{
System.out.println("Timer ran " + ++i);
if (i==5) {
timer.cancel();
timer.purge();
}
}
}
public class Test3
{
public static void main(String[] args)
{
Timer timer = new Timer();
Helper task = new Helper();
Helper.setTimer(timer);
timer.schedule(task, 0, 1000);
}
}

Why for loop does not execute inside TmerTask

I want to repeat a for loop inside below code inside a service every some time ,but it print only one line and runs one time only
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 10000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
for (int i=0; i<10; i++){
Log.i("TAG", " inside method ");}
}
};
}
You are calling the following method.
public void schedule(TimerTask task, long delay)
So the task executes only once after delay.
If you want to execute it periodically you need to call the bellow method.(you may pass same value for delay and period)
public void schedule(TimerTask task, long delay, long period)
Your another query is it prints first line only. Most probably this is an issue with the Log. try System.out.print() instead of Log.i() to debug.
class MyTimerTask extends TimerTask {
private int counter = 1;
public void run() {
timerHandler.post(new Runnable() {
public void run() {
Toast.makeText(this, "" + counter, Toast.LENGTH_SHORT).show();
counter++;
}
});
if (counter == 10) {
myTimer.cancel();
myTimer.purge();
}
}
}
//Thats the usage like on ButtonClick
MyTimerTask myTimerTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTimerTask, 500, 1000);
Do you really need to run Loop ?

Change length of Countdowntimer

I want to change the length of my Countdowntimer when it finishs. So I got a Random Number which changes everytime.
standby_time = 15000
standby_counter = new CountDownTimer(standby_time,1000) {
#Override
public void onTick(long millisUntilFinished) {
++standby_zaehler;
}
#Override
public void onFinish() {
...
standby_zaehler = 0;
rndm_groesse = 60000;
random_zahl = r.nextInt(rndm_groesse);
standby_time = random_zahl;
standby_counter.start();
}
};
Where is my fault ? The time is not changing and takes the first value (15sec)
The countdown timers time isnt ment to be changed. You can recreate the timer to alter the time but because you are looking to start it again inside the onFinish() method it would be wise to use a different implementation better suited for this task. The java.util.Timer class does this well.
private Timer timer = new Timer();
private int standby_zaehler = 0;
private Random r = new Random();
public void scheduleNextTimer() {
// reset our countdown
standby_zaehler = 0;
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// 1 second passed, remove it to the countdown
--standby_zaehler;
// we are finished counting down. get a new max seconds
if(standby_zaehler < 0) {
standby_zaehler = r.nextInt(60);
}
}
}, 1000, 1000);
}
As you can see we dont even need to create a new timer, just reset the number and begin again.

Associating timer with tables

I am new to timer's and don't know much about them .My problem is i am creating 2 tables dynamically, and when ever a table is create a timer for 10 mins is assigned to it. I.e. the user has to fill that table in 10 mins else the table will be destroyed. I tried a making a small demo in which i print stuff
The code is :
final Timer mytimers = new Timer();
Timer mytimers1 = new Timer();
mytimers1 = new Timer();
final long delay1 = 5*1000;
// mytimers = new Timer();
mytimers.schedule(new TimerTask() {
Long current1 = System.currentTimeMillis();
long check = current1;
#Override
public void run() {
Long current = System.currentTimeMillis();
System.out.println(current);
System.out.println("\n");
if((current1 + delay1)<current)
{
System.out.println("mytimmer is about to stop");
mytimers.cancel();
}
}
}, 100, 1000);
mytimers1.schedule(new TimerTask() {
#Override
public void run() {
Long current = System.currentTimeMillis();
System.out.println("in" + current);
}
}, delay1, 1000);
}
but when i tried implementing this int he final project it does not work as i have to make any variable inside the run a final , thus its value can not to be changed !!!
Please let what should i do !!Thank you
i have to make any variable inside the run a final , thus its value can not to be changed!
Either turn these variables into member variables or encapsulate these values in a proper class, instantiate the class and give a reference to that object to the timer task.
Even though the reference is final, the timer task will still be able to do things such as myTableController.destroyTable().
do it like this :
class YourClass{
Timer mytimers = new Timer();
Timer mytimers1 = new Timer();
long delay1 = 5*1000;
mytimers.schedule(new TimerTask() {
Long current1 = System.currentTimeMillis();
long check = current1;
#Override
public void run() {
Long current = System.currentTimeMillis();
System.out.println(current);
System.out.println("\n");
if((current1 + delay1)<current) {
System.out.println("mytimmer is about to stop");
mytimers.cancel();
}
}
}, 100, 1000);
mytimers1.schedule(new TimerTask() {
#Override
public void run() {
Long current = System.currentTimeMillis();
System.out.println("in" + current);
}
}, delay1, 1000);
}
in your case you have created anonymous 'concrete' class ie TimerTask, and you are trying to access variables which are not in its scope.
So, if the variables you are trying to access are local(method) variables then they should be declared final or the other way around is to declare those variables as instant(member) variables that what i have done above.

Categories