Solved

j2me question..repeat the timertask with if condition

Posted on 2004-07-31
25
1,032 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
  • 13
  • 12
25 Comments
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
Comment Utility
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
Comment Utility
:(
the code crash with other classes and functions...
all my animations wouldnt move no matter what value i put for the DELAY
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>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
Comment Utility
>>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
Comment Utility
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
Comment Utility
>>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
Comment Utility
>>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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
i uploaded the file to geocities... hope it is able to download
http://www.geocities.com/woo_san2000/AnimationTest.zip
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 86

Expert Comment

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

Author Comment

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

Author Comment

by:lalilulelo
Comment Utility
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
Comment Utility
>>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
Comment Utility
>>Do an experiment -

Forget that for the moment
0
 

Author Comment

by:lalilulelo
Comment Utility
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
Comment Utility
emmm.... the time here is 3am ...im going to sleep... see you tomorrow
0
 
LVL 86

Expert Comment

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

Author Comment

by:lalilulelo
Comment Utility
ooo ok.... thank alot....
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 50 total points
Comment Utility
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
Comment Utility
wow.... you are awesome...

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

Expert Comment

by:CEHJ
Comment Utility
No problem ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
8-)
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.

763 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now