-1

I'm looking for a way to do something every X minutes.

For example in a game you will be playing then every 3 minutes activate

foo();

but I'm not sure how to do this given that other actions will be going on. Ie, we cannot just wait 3 minutes then do foo() instead the rest of the program must be running and the user can invoke other methods but in the background we have to be counting and getting ready to do foo() when the time is ready.

If anyone can give me a starting point I'd much appreciate it!

Alex
  • 627
  • 3
  • 12
  • 32
  • 2
    What type of GUI library? Swing? JavaFx? Android? – Hovercraft Full Of Eels Nov 26 '14 at 21:25
  • 1
    Related, possibly duplicate of: [How do I schedule a task to run at periodic intervals?](http://stackoverflow.com/q/4544197/877472) – Paul Richter Nov 26 '14 at 21:25
  • Just standard java for now. Just let's say it is text based for simplicity? – Alex Nov 26 '14 at 21:26
  • See [this tutorial](http://docs.oracle.com/javase/tutorial/essential/concurrency/). Basically: create and start a new `Thread` with a method that calls `Thread.sleep(3000); foo();` in a loop (3000 is in milliseconds). But depending on what `foo` does, you may have to take other actions to ensure that things are synchronized and that you don't have `foo` and the rest of your program interfere with each other if they modify data or something. If you are using Swing then there are other things you need to study first. – ajb Nov 26 '14 at 21:26
  • 2
    Use `scheduleAtFixedRate()`: http://www.tutorialspoint.com/java/util/timer_scheduleatfixedrate_delay.htm – Matjaž Nov 26 '14 at 21:28
  • I gave you an answer John – Roberto Anić Banić Nov 26 '14 at 21:29
  • @ajb That's every 3 seconds, not 3 minutes. `Thread.sleep(3 * 1000 * 60)` would be three minutes. – Bryan Davis Nov 26 '14 at 21:38
  • @BryanDavis Sorry, misread the question. – ajb Nov 26 '14 at 22:31

5 Answers5

7

You want some manner of separate thread that has a timer in it. A built in structure is the ScheduledExecutorService.

A tutorial on how to use one can be found here

The tutorial is kind of confusing and ugly, so here it is summarized in three steps:

1) Define a thread executor (something that manages your threads)

int x = 1; // However many threads you want
ScheduledExecutorService someScheduler = Executors.newScheduledThreadPool(x); 

2) Create a Runnable class, which contains whatever it is you want to do on a schedule.

public class RunnableClass implements Runnable {
   public void run() {
       // Do some logic here
   }
}

3) Use the executor to run the Runnable class on whatever level of your program you want

Runnable someTask = new RunnableClass(); // From step 2 above
long timeDelay = 3; // You can specify 3 what
someScheduler.schedule(someTask , timeDelay, TimeUnit.MINUTES);
Bryan Davis
  • 134
  • 6
1

Bryan Davis pointed the solution, but the link provided is not very elegant. here is a short sample:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3); 
// 3 = number of thread in the thread pool

scheduler.scheduleAtFixedRate(new Runnable() 
{
       public void run() 
       { 
           // do something here
       }

}, 20, TimeUnit.SECONDS);
ymz
  • 6,602
  • 1
  • 20
  • 39
1

For a single threaded game, you can just check every loop whether it is time to do foo(). For example:

long lastTime;
long timeBetweenFoosInMillis = 3*60*1000; //3 minutes
public void loop(){
    while(true){
        doOtherGameStuff();
        if(isFooTime()){
            foo();
            lastTime = System.currentTimeMillis();
        }
    }
}
private boolean isFooTime(){
    return System.currentTimeMillis() >= lastTime + timeBetweenFoosInMillis;
}
Kyranstar
  • 1,650
  • 2
  • 14
  • 35
0

You probably want to use Threads. You can put your foo() function in one and make it sleep and execute every X minutes, and put the rest of the program in other threads so your other functions can keep executing. Here is a good tutorial on how to set up a multi-thread program in java: http://www.oracle.com/technetwork/articles/java/fork-join-422606.html

jemendoza
  • 1
  • 1