Executor can return Executor, ExecutorService, and ScheduledExecutorService.
This is very, very usful Tiger new timer.
scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10, SECONDS);
4 arguments:
1) Runable or Callable, which is the task scheduled to run.
2) 0. When the first time to run. 0 seconds later, means, immediately.
3) 10. When next time run. 10 seconds later.
4) What's time unit. The argument 0, and 10, all use the time unit SECONDs.
package test;
import java.io.PrintStream;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.SECONDS;;
public class Thread5
{
public static void main(String[] args)
{
// Get the scheduler
//An alternative way to get scheduler is like this, you can simply replace with it
//ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(10);
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
// Get a handle, starting now, with a 10 second delay
final ScheduledFuture<?> timeHandle = scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10, SECONDS);
// Schedule the event, and run for 1 hour (60 * 60 seconds)
scheduler.schedule(new Runnable()
{
public void run()
{
timeHandle.cancel(false);
}
}, 60 * 60, SECONDS);
}//end of main
}
class TimePrinter implements Runnable
{
private PrintStream out;
public TimePrinter(PrintStream out)
{
this.out = out;
System.out.println("a TimePrinter instance is created");
}
public void run()
{
out.printf("Current time: %tr%n", new Date());
}
}
Summary:
Step 1) Get a ScheduledExecutorService --- Scheduler
Step 2) Tell the scheduler, which to run, how frequent, when to start. ---generate ScheduledFuture
Step 3) Start the Scheduler using schedule() method, wraping ScheduledFuture into Runnable, passing the Runnable to the schedule()