如何动态安排不同的java类?

时间:2015-06-29 14:13:37

标签: java scheduling

我正在尝试编写一个调度程序类,它可以调度在某个用户指定的计时器上设置的不同类。我正在使用

ScheduledExecutorService

ScheduleAtFixedRate

进行调度。我正在努力的是如何告诉调度程序要安排哪个Java类。

这个想法是你调用调度程序,在构造函数中会有一些字符串,这将是你想要安排的java类的名称。我在

中使用所述字符串时遇到问题
ScheduleAtFixedRate

因为它需要一个可运行的。有什么想法或建议吗?

3 个答案:

答案 0 :(得分:2)

为什么不让你的类实现Runnable接口并传递这些实例而不是传递每个类的名称并使用Reflection? (请记得在接收器部分中将您的课程称为Runnable,而不是您的班级名称

<强> __ UPDATE __

public interface Schedulable extends Runnable{
   //In case you need extra API. If not, you don't 
  //need this interface, just use Runnable instead.
}


public class ScheduleAtFixedRate implements Schedulable{
     public void run(){
         // run at fixed rate
     }
}


public class ScheduleAtVariableRate implements Schedulable{
     public void run(){
         // run at fixed rate
     }
}

public class ScheduledExecutorService{
    ...

    public void execute(Schedulable s){
         new Thread(s).start();
    }
    ...

}

答案 1 :(得分:0)

假设你有两个班级

public class ABC  extends TimerTask{ 
@Override
public void run()
{/*some code*/}


public class XYZ extends TimerTask{
@Override
public void run()
{/*some code*/}
}

然后从某个班级

public class ScheduleTheTask{

public static void main(String[] args) {
begin("com.ABC",new Date(),3000);
begin("com.XYZ",new Date(),3000);
}

   public static void begin(String task , Date startTime,long timeInMillisecons)


     {
                Class<?> clazz = Class.forName(task);
//BIG assumption that only TimerTask  subclasses would be passed add a instanceof check
                TimerTask taskObj= (TimerTask)clazz.newInstance();
                setStartTimeAndInterval();
                Timer timer = new Timer();
                timer.scheduleAtFixedRate(taskObj, startTime,timeInMillisecons);

            }
}

答案 2 :(得分:0)

您可以使用带有某个task_key(某个字符串)作为键和值的地图作为工作线程,即Runnable

以下是一个这样的例子

package com.test.thread;

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

public class ScheduleTask {

    private ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

    public void schedule(String task) throws InterruptedException {
        System.out.println("Current Time = "+new Date());
        scheduledThreadPool.scheduleAtFixedRate(getTasks().get(task), 0, 10, TimeUnit.SECONDS);

        Thread.sleep(30000);
    }

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

    public Map<String, Runnable> getTasks() {
        Map<String, Runnable> tasks = new HashMap<String, Runnable>();
        tasks.put("task1", new WorkerThread("task1"));
        tasks.put("task2", new WorkerThread("task2"));
        return tasks;
    }

    public static void main(String[] args) throws InterruptedException {
        ScheduleTask scheduleTask = new ScheduleTask();
        scheduleTask.schedule("task1");
        scheduleTask.schedule("task2");

    }
}