# Java - Timer ###### tags: `Java` `Basic Java` Java Timer有兩種 1. Timer 2. ScheduledExecutorService ## Timer示範: ``` public class TimerDemo { public static void main(String[] args) { // 1. create timer object Timer timer = new Timer(); // 2. use it on task timer.schedule(new TimerTask() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " executing..."); } }, 3000, 2000); } } ``` **BUT!!!!!!!!!** Timer是single thread,在使用上會產生許多不便,故還是比較建議使用第二種方式建立定時任務 ## ScheduledExecutorService 這個API是基於thread pool開發的,在開發中會比較常使用 ``` public class ScheduledExecutorDemo { public static void main(String[] args) { // 1. create a scheduled thread pool ScheduledExecutorService pool = Executors.newScheduledThreadPool(3); // 2. create scheduled task pool.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " executing..."); } }, 0, 2, TimeUnit.SECONDS); } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up