brushbrushbrush
brushbrushbrush

Reputation: 13

Executing code every x seconds

Im creating a GUI interface where the user enters a nimber into a textfield, the number is then added as a parameter to an object of CurrentAccount. This number is then added or subtracted to a randomised value. I want this to happen every 5 seconds, taking the value after the equation has been completed and adding or subtracting a value until the user tells it to stop. So far i have created this code to decide if a random number should be added of subtracted, generate the random number, add or subtract it to the account balance then print the account balance to a text field.

 //method generates a random number to determine if a value should be added or subtracted from the myBalance variable within theAccount classes and completes the equation
int month = 0;
private void simulate()
{
    try
    {
        if(month<12)
        { //Creates instance of Random to decide if the random number should be added or subtracted to the balance
            Random decider = new Random();
            for (int i = 0; i < 1; i++)
            {

                int ans = decider.nextInt(2)+1;

                //if the decider value == 1, subtract or "withdraw" random number from the balance
                if (ans == 1)

                {      
                    //creates instance of Random to create random number 
                Random bal = new Random();                
                    int withdrawAmount = bal.nextInt((500 - 100) + 1) + 100;

                    //sets account balance to the balance subtract the random number                    
                    theAccount.myBalance = theAccount.myBalance - withdrawAmount;   

                    //increments the month timer
                    month++;

                    //prints the new balance to the transaction text field
                   jTextArea2.setText("The new balance is " + theAccount.myBalance );
                } else
                { 
                    //if decider value == 2, add or "deposit" random number to the balance

                    //creates instance of Random to create random number 
                    Random bal = new Random();
                    int depositAmount = bal.nextInt((500 - 100) +1) + 100;

                    //sets account balance to the balance plus the random number
                    theAccount.myBalance= theAccount.myBalance + depositAmount;

                    //increments the month timer
                    month++;

                    //prints the new balance to the transaction text field
                    jTextArea2.setText("The new balance is " + theAccount.myBalance );
                }

                //if the account has a balance of -£200, generate an error and reset the balance to the user inputted value
                if (theAccount.myBalance < -200)
                {
                    jTextArea1.setText("Overdraft of £200 only");
                    theAccount.myBalance = value;
                }

                //if the account has a balance of 0, generate an error as the account must always have at least £1 before entering the overdraft
                if(theAccount.myBalance == 0)
                {
                    jTextArea1.setText("An account must always have £1");

                }

            }
        } 
    } catch (NullPointerException i)
    {
        jTextArea2.setText("Create an Account");
    }
}

ive tried using a thread.sleep(5000) method but must have put it in the wrong place as it stuck the create button for 5 seconds and printed out the balance on its own. Any help with this matter would be great. Also i have a method to detect the user input and obviously an action listener on the button to call it and this method.

[amended comment] I also tried to use a timer to loop the code but i cant seem to get it pointed at the right code to repeat as it just doesn't do anything other than fill up memory.

 ActionListener timerListener = new ActionListener() 
        {
            public void actionPerformed(ActionEvent evt) 
            {
                ControlPanel.this.simulate();
            }
        };
       Timer theTimer = new Timer(5000,timerListener);

Upvotes: 1

Views: 6548

Answers (2)

jakubbialkowski
jakubbialkowski

Reputation: 1566

Another way to run periodic task could be using ScheduledExecutorService

Then your code could look like this:

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

Runnable yourRunnable = new Runnable() {
    @Override
    public void run() {

        // Implement your Code here!

     }
};

And then run your task:

int initialDelay = 0;
int delay = 5;
scheduler.scheduleWithFixedDelay(yourRunnable, initialDelay, delay, TimeUnit.SECONDS);

Your task may be cancelled with invoking method shutdown()

scheduler.shutdown(); 

Upvotes: 4

Marcinek
Marcinek

Reputation: 2117

Here you are an example for the java.util.Timer:

We need a task to be called by the Timer: MyTimerTask

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

public class TimerTaskExample extends TimerTask {

    @Override
    public void run() {

        // Implement your Code here!
    }
}

Then we have to schedule a Timer to execute this Task:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 0, 10 * 1000);

The first argument is the Task to be executed.

The second parameter states a delay before the first execution.

The third parameter is the period in milliseconds. (Here: Execute every 10 Seconds!)

Please note that if you want to do things in your GUI with this mechanism you need to use SwingUtilities.invokeLater()


Supplemental after edit:

To use javax.swing.Timer you have to call start() to make the timer run.

Upvotes: 2

Related Questions