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

How to schedule different java classes dynamically?

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

ScheduledExecutorService

ScheduleAtFixedRate

进行调度。我正在努力解决的问题是如何告诉调度器要调度哪个 Java class。

我们的想法是您将调用调度程序,并且在构造函数中将是一些字符串,这将是您要安排的 java class 的名称。我在

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

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

为什么不让 classes 实现 Runnable 接口并传递这些实例,而不是传递每个 class 的名称并使用反射? (请记住在接收器部分将您的 classes 称为 Runnable,而不是您的 class 名称

__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();
    }
    ...

}

假设您有两个 classes

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


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

然后从一些 class

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);

            }
}

您可以使用带有一些 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");

    }
}