2014-10-08 38 views
0

我已經寫了一個代碼發送電子郵件給正在正常工作的用戶。 但是,我想添加一個計時器,通過設置它在特定的時間間隔自動發送電子郵件給用戶。如何使用定時器自動調用函數?

所以需要幫助才能知道如何才能做到這一點..

+1

你用google搜索了一下,例如用crontab表達式看石英計時器嗎? – vikingsteve 2014-10-08 12:10:54

回答

1

你可以嘗試類似這樣的一個結構:

public class TestClass { 
    public long myLong = 1234; 

    public static void main(String[] args) { 
     final TestClass test = new TestClass(); 

     Timer timer = new Timer(); 
     timer.schedule(new TimerTask() { 

      @Override 
      public void run() { 
       test.doStuff(); 
      } 
     }, 0, test.myLong); 
    } 

    public void doStuff(){ 
     //do stuff here 
    } 
} 
0

現代的方式做到這一點是使用ScheduledExecutorService,這由約書亞布洛赫在 「有效的Java」 推薦:

final int initialDelay = 0; // the initial delay in minutes (or whatever you specify below) 
final int period = 5; // the period in minutes (...) 
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor(); 
ex.scheduleAtFixedRate(new Runnable() { 
    @Override 
    public void run() { 
     sendEmail(); 
    } 
}, initialDelay, period, TimeUnit.MINUTES); 
// or, with Java 8: 
ex.scheduleAtFixedRate(() -> sendEmail(), initialDelay, period, TimeUnit.MINUTES); 
// when finished: 
ex.shutdown(); 

見的javadoc ScheduledExecutorServicehttp://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

相關問題