Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - How do you make something like a thread that can be started and stopped?

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.

like image 901
bigbass1997 Avatar asked Jan 16 '12 17:01

bigbass1997


2 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);
like image 90
Kiril Avatar answered Sep 18 '22 06:09

Kiril


You can use the java.util.Timer class to schedule tasks on a background worker thread.

like image 27
Tudor Avatar answered Sep 17 '22 06:09

Tudor