2014-06-16 52 views
0

有沒有什麼辦法在java中編寫程序,以便它的主要方法調度(或以10-15分鐘的間隔)另一種方法在特定的時間間隔執行它?如何在java的特定時間執行方法?

+2

您可以使用調度http://quartz-scheduler.org/ –

+0

ÿ你可以使用cron作業。 – Thilo

回答

1

我認爲你正在尋找的時間類。

Timer Class API 你可以使用這個類,如:

要執行一個方法每600毫秒。你寫:

ActionListener taskPerformer = new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent evt) { 
       //Do your stuff 
       } 
      }; 

Timer t = new Timer(600, taskPerfomer); 
t.start; 

有更多的選項。這個例子將被執行一次,但它可以間隔執行。 我希望它有幫助。

+1

該解決方案只能單次執行該方法。如果你想以微粒間隔執行它,你必須使用調度程序。 – Nitul

4

您可以使用Job scheduler來做到這一點。即
石英Job Scheduler

請參閱本Quartz API

或者 您可以使用ScheduledExecutorService的Java接口

請參閱本Documentation

1

使用預定線程池執行程序: 安排工作線程每隔10秒執行一次 scheduledThreadPool.schedule(worker,10,TimeUnit.SECONDS);

1)班的WorkerThread的.java

public class WorkerThread implements Runnable{ 

private String command; 

    public WorkerThread(String s){ 
     this.command=s; 
    } 

    @Override 
    public void run() { 
     System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date()); 
     processCommand(); 
     System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date()); 
    } 

    private void processCommand() { 
     try { 
      Thread.sleep(5000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public String toString(){ 
     return this.command; 
    } 
} 

2)班ScheduledThreadPool的.java

import java.util.Date; 
import java.util.concurrent.Executors; 
import java.util.concurrent.ScheduledExecutorService; 
import java.util.concurrent.TimeUnit; 


public class ScheduledThreadPool { 

    public static void main(String[] args) throws InterruptedException { 
     ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); 


     //schedule to run after sometime 
     System.out.println("Current Time = "+new Date()); 
     for(int i=0; i<3; i++){ 
      Thread.sleep(1000); 
      WorkerThread worker = new WorkerThread("do heavy processing"); 
      scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS); 
     } 

     //add some delay to let some threads spawn by scheduler 
     Thread.sleep(30000); 

     scheduledThreadPool.shutdown(); 
     while(!scheduledThreadPool.isTerminated()){ 
      //wait for all tasks to finish 
     } 
     System.out.println("Finished all threads"); 
    } 

} 
-1

如果你的任務不是那麼大,你可以使用Thread.sleep()方法(例如10迭代與10分鐘延遲):

public static void main(String[] args) throws InterruptedException { 
    methodOne(); 

    for (int i = 0; i < 10; i++) { 
    Thread.sleep(600000); 
    methodTwo(); 
    } 
}