How to Use a Timertask to Run a Thread

How do you use a TimerTask to run a thread?

You use a Timer, and that automatically creates a new Thread for you when you schedule a TimerTask using any of the schedule-methods.

Example:

Timer t = new Timer();
t.schedule(myTimerTask, 1000L);

This creates a Timer running myTimerTask in a Thread belonging to that Timer once every second.

Timer & TimerTask versus Thread + sleep in Java

The advantage of TimerTask is that it expresses your intention much better (i.e. code readability), and it already has the cancel() feature implemented.

Note that it can be written in a shorter form as well as your own example:

Timer uploadCheckerTimer = new Timer(true);
uploadCheckerTimer.scheduleAtFixedRate(
new TimerTask() {
public void run() { NewUploadServer.getInstance().checkAndUploadFiles(); }
}, 0, 60 * 1000);

Android how to run thread for each 25 ms?

Use a ScheduledExecutorService:

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(/* Your Runnable */, 0, 25, TimeUnit.MILLISECONDS);

Or RxJava:

Flowable.interval(0, 25, TimeUnit.MILLISECONDS).subscribe(/* Code to execute */);

Java Timer Thread Operation

Actually, your application is probably still running (or should be), regardless of the scheduled timeout. According to the JavaDocs, creating a Timer using the default constructor will create a user thread, so it's "capable of keeping an application from terminating".

If you run the application with a debugger, you should see the timer thread being kept alive in the background as something like


Thread[Timer-0](Running)

Changing the Timer to use a daemon thread instead with

Timer timer = new Timer(true);

will show that the thread actually terminates immediately with the rest of the program when main() finishes:


terminated, exit value 0

Trying your code with ideone also verifies that the program doesn't terminate after main(), but instead continues execution until the JVM is terminated (there's a built-in five-second timeout), after which the expected output is printed.

Whether or not the output is printed at the scheduled time or when the application exits, is probably dependent on the underlying OS and JVM.



Related Topics



Leave a reply



Submit