You can learn ScheduledThreadPoolExecutor instead of Timer .
Use is pretty straight forward. You create an instance of the executor:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1 );
And then when you want to add the task that you are calling:
executor.scheduleAtFixedRate( myRunnable, delay, interval, unit );
Where myRunnable is your task (which implements Runnable -interface), the delay is how long before the task needs to be completed for the first time, interval is the time between the execution of the task after the first execution. delay and interval are evaluated based on the unit parameter, which may be TimeUnit. * (where * - SECONDS, MINUTES, MILLISECONDS, etc.).
Then, to stop execution, you call:
executor.shutdownNow();
And then you can resubmit your task at a different interval.
Note. You may need to create a new instance of the artist before resubmitting your task, but I donβt quite understand why.
source share