• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1047
  • Last Modified:

j2me question..repeat the timertask with if condition

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
lalilulelo
Asked:
lalilulelo
  • 13
  • 12
1 Solution
 
CEHJCommented:
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
 
laliluleloAuthor Commented:
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
 
laliluleloAuthor Commented:
:(
the code crash with other classes and functions...
all my animations wouldnt move no matter what value i put for the DELAY
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
CEHJCommented:
>>what should i put for the DELAY?

Depends on how often you want to check the energy level. 5000? (every 5 secs)
0
 
CEHJCommented:
>>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
 
laliluleloAuthor Commented:
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
 
CEHJCommented:
>>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
 
CEHJCommented:
>>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
 
laliluleloAuthor Commented:
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
 
CEHJCommented:
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
 
laliluleloAuthor Commented:
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
 
laliluleloAuthor Commented:
i uploaded the file to geocities... hope it is able to download
http://www.geocities.com/woo_san2000/AnimationTest.zip
0
 
CEHJCommented:
Sorry - don't do or have J2ME. Just study and run the example i gave you carefully
0
 
laliluleloAuthor Commented:
oooo ok.... anyway, thanks for helping.... i try to understand it...
and tell you the result later...
0
 
laliluleloAuthor Commented:
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
 
CEHJCommented:
>>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
 
CEHJCommented:
>>Do an experiment -

Forget that for the moment
0
 
laliluleloAuthor Commented:
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
 
laliluleloAuthor Commented:
emmm.... the time here is 3am ...im going to sleep... see you tomorrow
0
 
CEHJCommented:
Just wait a minute, as i can give you something that's nearer to your requirement
0
 
laliluleloAuthor Commented:
ooo ok.... thank alot....
0
 
CEHJCommented:
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
 
laliluleloAuthor Commented:
wow.... you are awesome...

the example is what i wanted so far... thaks alot...
0
 
CEHJCommented:
No problem ;-)
0
 
CEHJCommented:
8-)
0

Featured Post

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!

  • 13
  • 12
Tackle projects and never again get stuck behind a technical roadblock.
Join Now