我正在尝试编写一个调度器类,该类可以调度在某个用户指定的计时器上设置的不同类。我正在使用
ScheduledExecutorService
和
ScheduleAtFixedRate
进行日程安排。我正在努力解决的问题是如何告诉调度器要调度哪个Java类。
这个想法是,你可以调用调度器,在构造函数中会有一些字符串,这将是你想要调度的java类的名称。我在中使用所述字符串时遇到问题
ScheduleAtFixedRate
因为它需要一个可运行的。有什么想法或建议吗?
为什么不让类实现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();
}
...
}
假设您有两个类
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);
}
}
您可以使用一个映射,其中一些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");
}
}