如何在java中的特定时间执行方法?

时间:2014-06-16 09:42:08

标签: java methods cron clock jobs

有没有办法在java中编写程序,以便它的主要方法计划(或以10-15分钟的间隔)另一种方法以特定的间隔执行它?

4 个答案:

答案 0 :(得分:4)

您可以使用Job scheduler。即
Quartz Job Scheduler

请参阅此Quartz API

或者 您可以使用 ScheduledExecutorService Java接口

请参阅此Documentation

答案 1 :(得分: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;

还有更多选择。此示例将执行一次,但可以在一个间隔中执行。 我希望它有所帮助。

答案 2 :(得分: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)Class 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");
    }

}

答案 3 :(得分:-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();
   }
}