Is there a way to make something like a thread that does something every x amount of ms that I can start, stop, and resume when I want it to? I know that a thread can be started but there is no real safe way to stop and resume a thread.
-
Have a look at http://www.quartz-scheduler.org/ – Paul Medcraft Jan 16 '12 at 18:01
5 Answers
Here are a bunch of examples on how to start/stop periodic tasks in Java:
- How to schedule a periodic task in Java? (basically executor service)
- Schedule periodic tasks (a more detailed exploration into various ways to schedule periodic tasks)
The example from the first link:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, HOURS);
You can use the java.util.Timer class to schedule tasks on a background worker thread.

- 61,523
- 12
- 102
- 142
-
-
1@Scorpion: If the task is simple, there is no need to use more complicated constructs. – Tudor Jan 16 '12 at 18:04
-
Tudor: using ScheduledExecutorService isn't complicated (atleast not more complicated than using Timers) as illustrated by @Lirik's answer. Also, this (http://stackoverflow.com/questions/409932/java-timer-vs-executorservice) discussion should give you some insight why Timer should be avoided. – Scorpion Jan 17 '12 at 07:46
The javadocs of the thread pol executor has an example of creating a thread pool which can be paused/ resumed. Here is the link http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html
It is not of industrial strength but should be enough to give you ideas.

- 3,938
- 24
- 37
I believe what you're looking for is the Timer class, which will allow you to periodically executes the run method of a sub-class of TimerTask.
For recurring events, the example given at http://enos.itcollege.ee/~jpoial/docs/tutorial/essential/threads/timer.html (slightly modified and copied here for convenience) is :
public class AnnoyingMessage {
Timer timer;
public AnnoyingBeep() {
timer = new Timer();
timer.schedule(new RemindTask(),
0, //initial delay
1*1000); //subsequent rate = once a second.
}
class RemindTask extends TimerTask {
int numWarningBeeps = 3;
public void run() {
if (numWarningBeeps > 0) {
System.out.println(" MESSAGE!");
numWarningBeeps--;
} else {
System.out.println("Done");
timer.cancel();
}
}
}
}

- 303
- 1
- 4
There are definitely safe ways to stop threads. Read http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html. And pausing a thread and resuming it is simply a matter of setting a flag and using wait
and notifyAll
appropriately.
You're probably looking for a higher-level abstraction, though. Have a look at ScheduledExecutorService
.

- 678,734
- 91
- 1,224
- 1,255