Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

j2me question..repeat the timertask with if condition

Posted on 2004-07-31
25
Medium Priority
?
1,045 Views
Last Modified: 2013-11-23
TimerTask task1a = new TimerTask()
 {
    public void run()
    {           
     if(energy==0){timer.schedule(task4, 10000);}
    }
 };

TimerTask task4 = new TimerTask()  
 {
    public void run()
    {
    energy=energy+2;
    }
 };
//////////////////////////////////////////////////////////////////////
The codes above is to wake up the pet during sleeping

1)the pet will sleep when energy == 0
2)then task1a will activate the task4 with delay of 10 seconds
3)task4 to fill the energy with 2 and so the pet wake up

but the code only work one time that means the first time pet sleep,
it will wake up after sleep for 10 seconds.
but the second time the pet will sleep forever.


the expected fault is "timer.schedule(task4, 10000);"
*the timertask happened only one time and will not execute the second time.
*i cant modify to this "timer.schedule(task4, 10000, 10000);"
because the task activate by condition but not timer

so guys any suggestion to correct my codes fault.... im running out of idea
0
Comment
Question by:lalilulelo
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 13
  • 12
25 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 11683864
You seem to need something like:



TimerTask task1a = new TimerTask() {
      public void run() {
            for(;;) {
                  if(energy == 0) {
                        timer.schedule(task4, 10000);
                  }
                  else {
                        try {
                              Thread.sleep(DELAY); // adjust DELAY
                        }
                        catch(Exception e) {
                              e.printStackTrace();
                        }
                  }
            }
      }
};

Make sure the other task gets cancelled when energy is 'full'
0
 

Author Comment

by:lalilulelo
ID: 11683979
well, thank you for the soultion....

im trying to understand the codes given...
i would like to know how it works....

1)what should i put for the DELAY?
0
 

Author Comment

by:lalilulelo
ID: 11683991
:(
the code crash with other classes and functions...
all my animations wouldnt move no matter what value i put for the DELAY
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 11684011
>>what should i put for the DELAY?

Depends on how often you want to check the energy level. 5000? (every 5 secs)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11684037
>>i would like to know how it works....

The first task checks the energy level. If it's 0 it schedules the other timer to increment it. If it's not, it sleeps for DELAY milliseconds then checks again. This is in a loop
0
 

Author Comment

by:lalilulelo
ID: 11684103
oooo ic... actuary i have another timer to check the energy level

 protected void startApp() throws MIDletStateChangeException {
          hunger=10;
          energy=1;
             bladder=10;
          fun=10;
          sick=0;
         if(display==null){
         display = Display.getDisplay( this );
          timer.schedule( task, 0, 1000);    // a loop to update display every 1 second
          timer.schedule( task1, 0, 1000);   // a loop to check sick status every 1 second
          timer.schedule( task1a, 0, 1000);  // a loop to check sleep status every 1 second  (this one)
          timer.schedule( task1b, 0, 1000);  // a loop to check wake up status every 1 second
          timer.schedule( task1c, 0, 1000);  // a loop to check fatal status every 1 second
        timer.schedule( task2, 60000, 60000 ); // a loop to update all status every 1 minutes
      }
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
if the  "for(;;) { }" included in the task1a, the program wouldnt work...
if i dont include, the dog also sleep forever after 1st sleep
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11684134
>>the program wouldnt work...

In what way?

You set the energy level to 1, so that task4 will be scheduled right way and will run after its delay.

You should probably sleep the timer in task4:

Thread.sleep(SOME_DELAY);
energy += 2;

If nothing else is depleting the energy, task4 will probably not get scheduled again
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11684155
>>so that task4 will be scheduled right way and will run after its delay.

Sorry - that should have said

so that task4 won't be scheduled right way. In fact, if nothing is depleting the energy level, task4 will never be scheduled
0
 

Author Comment

by:lalilulelo
ID: 11684160
hi CEHJ.... i understanded your codes already... basically it perform the same effect of my original code does

the problem still here....

    timer.schedule(task4, 10000);

the task will activate for the first "if(energy==0)", my code will recheck the energy level every 1 second

but the task4 has activated for the first time by delay of 10 seconds.... it never activate again when the "if(energy==0)" calls it again..

i tried to cancel the task4 also.... then the task4 canceled and couldnt create another new task4

basically i need something to reset the task4 when the if(energy==0) happen again...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11684444
This is the sort of thing i'm getting at. Run it and you'll see the program cycles through incrementing and checking the energy level. Watch the command line for

'ENERGY LEVEL 0! Please refill'

and

'Refilling energy - level now <level>


SNIP======================================================


import java.util.Timer;
import java.util.TimerTask;

public class EnergyTasks {
      
      private Timer timer;
      private Timer levelSetterTimer;
      private int energyLevel;
      
      public EnergyTasks() {
            timer = new Timer();
            levelSetterTimer = new Timer();
      }
      
      public void scheduleCheckerTaskNow() {
            timer.schedule(new EnergyLevelChecker(), 0);
      }


      public static void main(String[] args) {
            EnergyTasks et = new EnergyTasks();
            et.scheduleCheckerTaskNow();
      }


      class EnergyLevelChecker extends TimerTask {

            private final static int ENERGY_CHECKER_DELAY = 10;

            public void run() {
                  for (; ; ) {
                        if (energyLevel == 0) {
                              System.out.println("ENERGY LEVEL 0! Please refill");
                               levelSetterTimer.schedule(new EnergyLevelSetter(), 100);
                        }
                        else {
                              try {
                                    Thread.sleep(ENERGY_CHECKER_DELAY);
                                    // adjust DELAY
                              }
                              catch (Exception e) {
                                    e.printStackTrace();
                              }
                        }
                  }
            }
      }

      class EnergyLevelSetter extends TimerTask {

            private final static int ENERGY_SETTER_DELAY = 100;
            private final static int ENERGY_LEVEL_INCREMENT = 10000000;


            public void run() {
                  for (; energyLevel >= 0; ) {
                        try {
                              Thread.sleep(ENERGY_SETTER_DELAY);
                              // energyLevel will overflow the int and stop the loop
                              energyLevel += ENERGY_LEVEL_INCREMENT;
                              System.out.println("Refilling energy - level now " + energyLevel);

                        }
                        catch (Exception e) {
                              e.printStackTrace();
                        }
                  }
                  energyLevel = 0;

            }
      }
}
0
 

Author Comment

by:lalilulelo
ID: 11684529
Hi CEHJ...
i having problem to implement your idea into my project... i have no idea why the code you given to me is not working in my project...
is there any way i can send you my file, so you can have a look... it requires Ktoolbar to run..
0
 

Author Comment

by:lalilulelo
ID: 11684657
i uploaded the file to geocities... hope it is able to download
http://www.geocities.com/woo_san2000/AnimationTest.zip
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11685744
Sorry - don't do or have J2ME. Just study and run the example i gave you carefully
0
 

Author Comment

by:lalilulelo
ID: 11687106
oooo ok.... anyway, thanks for helping.... i try to understand it...
and tell you the result later...
0
 

Author Comment

by:lalilulelo
ID: 11688778
Hi CEHJ... is that ok to keep on disturbing you? im studying your code...
there is a doubt about the code, i have no idea y the energy increasement wouldnt stop for a certain level...(sorry, im very stupid for learning)

is there anyway to stop it? example the min of energy level is 0 and max is 10.. when energy level=0 will start the increasement to 10 and stop.

(my main purpose)
i try to implement another timertask to deduct the energy level of 1 in maybe 10 seconds to test if the code can do the increasement if the energy level turn to 0 again...  
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11689140
>>i have no idea y the energy increasement wouldnt stop for a certain level

You could make it stop. It just so happens that my code keeps increasing an int. When you do that, it eventually becomes negative (then i set it to 0), hence the cyclical effect in my example.
Otherwise it would have just run once. Do an experiment - just put an upper limit on the 'energy increaser' and you'll see it only runs through one cycle

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11689148
>>Do an experiment -

Forget that for the moment
0
 

Author Comment

by:lalilulelo
ID: 11689164
ooooo ok.... .... but i almost got your example's idea...

one question....

    levelSetterTimer.schedule(new EnergyLevelSetter(), 100);

the "new EnergyLevelSetter()" been called to increase the energy level...
can you suggest a way to cancel the task of EnergyLevelSetter()?

now i have a new class

public class wakeup extends TimerTask{
      Timer x = new Timer();
      
      TimerTask taskx = new TimerTask()  
       {
          public void run()
          {
          energy=energy+2;
          }
       };
      
      
      public void run() {
            
      x.schedule(taskx, 10000);

      }
}
////////////////////////////////////////////////////////////////////////////////////

so when energy==0 this code will call the new class..
/////////////////////////////////////////////////////////////////////////////////////
TimerTask task1a = new TimerTask()
 {
    public void run()
    {       
     if(energy==0){timer.schedule(new wakeup(), 1);}  
    }  
   
 };

///////////////////////////////////////////////////////////////////////////////////

and then i shall cancel the task when energy==10
////////////////////////////////////////////////////////////////////////////////////
TimerTask task1b = new TimerTask()
 {
    public void run()
    {       
     if(energy==10){????????????????what is the magic code here??????????????;)
    }
 };

//////////////////////////////////////////////////////////////////////////////////////
i hope this idea going to work because currently this idea can compile and execute but the energy level also wouldnt stop raising....i need something to get it stop when energy==10
0
 

Author Comment

by:lalilulelo
ID: 11689183
emmm.... the time here is 3am ...im going to sleep... see you tomorrow
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11689197
Just wait a minute, as i can give you something that's nearer to your requirement
0
 

Author Comment

by:lalilulelo
ID: 11689209
ooo ok.... thank alot....
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 200 total points
ID: 11689230
Here we are - this is clearer and nearer to what you want i think. The checking thread runs a bit more often for obvious reasons:

SNIP==============================================


import java.util.Timer;
import java.util.TimerTask;

public class EnergyTasks2 {

      private Timer timer;
      private Timer increaserLevelTimer;
      private Timer decreaserLevelTimer;
      private int energyLevel;
      public final static int ENERGY_LEVEL_MAX = 10;
      public final static int ENERGY_LEVEL_MIN = 0;

      public synchronized void setEnergyLevel(int energyLevel) {
            this.energyLevel = energyLevel;
      }

      public synchronized int getEnergyLevel() {
            return energyLevel;
      }


      public EnergyTasks2() {
            timer = new Timer();
            increaserLevelTimer = new Timer();
            decreaserLevelTimer = new Timer();
      }

      private void scheduleCheckerTaskNow() {
            timer.schedule(new EnergyLevelChecker(), 0);
      }

      private void runEnergyIncreaser() {
            increaserLevelTimer.schedule(new EnergyLevelIncreaser(), 0);
      }

      private void runEnergyDecreaser() {
            decreaserLevelTimer.schedule(new EnergyLevelDecreaser(), 0);
      }




      public static void main(String[] args) {
            EnergyTasks2 et = new EnergyTasks2();
            et.scheduleCheckerTaskNow();
      }


      class EnergyLevelChecker extends TimerTask {

            private final static int ENERGY_CHECKER_DELAY = 500;

            public void run() {
                  for (; ; ) {
                        if (getEnergyLevel() == ENERGY_LEVEL_MIN) {
                              System.out.println("ENERGY LEVEL " + ENERGY_LEVEL_MIN + "! Refilling...");
                              runEnergyIncreaser();
                        }
                        else if (getEnergyLevel() == ENERGY_LEVEL_MAX) {
                              System.out.println("ENERGY LEVEL " + ENERGY_LEVEL_MAX + "! Decreasing...");
                              runEnergyDecreaser();
                        }
                        try {
                              Thread.sleep(ENERGY_CHECKER_DELAY);
                              // adjust DELAY
                        }
                        catch (Exception e) {
                              e.printStackTrace();
                        }
                  }
            }
      }

      class EnergyLevelIncreaser extends TimerTask {

            private final static int ENERGY_SETTER_DELAY = 1000;
            private final static int ENERGY_LEVEL_INCREMENT = 1;


            public void run() {
                  for (; getEnergyLevel() <= ENERGY_LEVEL_MAX; ) {
                        try {
                              Thread.sleep(ENERGY_SETTER_DELAY);
                              setEnergyLevel(getEnergyLevel() + ENERGY_LEVEL_INCREMENT);
                              System.out.println("Refilling energy - level now " + energyLevel);

                        }
                        catch (Exception e) {
                              e.printStackTrace();
                        }
                  }
            }
      }

      class EnergyLevelDecreaser extends TimerTask {

            private final static int ENERGY_SETTER_DELAY = 1000;
            private final static int ENERGY_LEVEL_INCREMENT = -1;


            public void run() {
                  for (; getEnergyLevel() >= ENERGY_LEVEL_MIN; ) {
                        try {
                              Thread.sleep(ENERGY_SETTER_DELAY);
                              setEnergyLevel(getEnergyLevel() + ENERGY_LEVEL_INCREMENT);
                              System.out.println("Decreasing - level now " + getEnergyLevel());

                        }
                        catch (Exception e) {
                              e.printStackTrace();
                        }
                  }
            }
      }

}

0
 

Author Comment

by:lalilulelo
ID: 11689251
wow.... you are awesome...

the example is what i wanted so far... thaks alot...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11689255
No problem ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11689257
8-)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question