簡體   English   中英

如何在特定時間在Java中執行方法?

[英]How do I execute a method at a particular time in java?

有什么方法可以用Java編寫程序,以便其主要方法調度(或以10-15分鍾為間隔)另一個以特定間隔執行的方法?

您可以為此使用Job Scheduler。
石英作業調度程序

參考這個Quartz API

或者您可以使用ScheduledExecutorService Java接口

請參閱此文檔

我認為您正在尋找時間課程。

請參見Timer類API。您可以使用此類,例如:

您想每600毫秒執行一次方法。 你寫:

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

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

還有更多選擇。 此示例將執行一次,但可以間隔執行一次。 希望對您有所幫助。

使用計划線程池執行程序:安排您的工作線程每10秒執行一次scheduleThreadPool.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");
    }

}

如果您的任務不是很大,則可以使用Thread.sleep()方法(例如10次迭代(延遲10分鍾)):

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM