在Java中使用ScheduledExecutorService定期运行任务
我正在开发一个程序,该程序将从数据源读取数据,并在读取时发布该数据。我有一个读卡器和一个写卡器,读卡器生成几个线程来读取它需要读取的所有数据,将数据放入一个队列,写卡器从队列中读取数据并发布数据 我有一个供我的读者使用的控制器和一个供我的作者使用的控制器。控制器实现了在Java中使用ScheduledExecutorService定期运行任务,java,executorservice,java-threads,Java,Executorservice,Java Threads,我正在开发一个程序,该程序将从数据源读取数据,并在读取时发布该数据。我有一个读卡器和一个写卡器,读卡器生成几个线程来读取它需要读取的所有数据,将数据放入一个队列,写卡器从队列中读取数据并发布数据 我有一个供我的读者使用的控制器和一个供我的作者使用的控制器。控制器实现了Callable接口,但可以实现Runnable接口,因为我的呼叫返回是Void 我想用一个执行器来运行这两个控制器。读卡器控制器需要每X分钟调用一次(X大于控制器运行所需的时间) 现在,我正在创建一个可调用项的列表,将它们发送到一
Callable
接口,但可以实现Runnable
接口,因为我的呼叫返回是Void
我想用一个执行器来运行这两个控制器。读卡器控制器需要每X分钟调用一次(X大于控制器运行所需的时间)
现在,我正在创建一个可调用项的列表
,将它们发送到一个ExecutorService,即:
List<Future<Void>> futures = ExecutorService es = new Executors.newFixedThreadPoll(2);
for(Future<Void> future: futures) {
try {
future.get();
} catch (Exception e) {
// log the error
}
}
List futures=Executors=newexecutors.newFixedThreadPoll(2);
for(未来:未来){
试一试{
future.get();
}捕获(例外e){
//记录错误
}
}
如何将其转换为每30分钟(或者更准确地说,在上一个作业运行后30分钟)运行一次callables的调度执行器?好的,您可以通过几种方法来实现。但是,如果性能非常重要,您可以在自己的线程中像这样处理这些事情:
public class TaskTimer extends Thread {
private java.util.concurrent.LinkedBlockingQueue<Runnable> taskQueue;
private int timeToWait;
private Long lastTime = -1l;
public TaskTimer(int time)
{
if(time<0)
throw new IllegalStateException("time can not negative");
timeToWait = time;
taskQueue = new java.util.concurrent.LinkedBlockingQueue<>();
}
void scheduleTask(Runnable task) throws InterruptedException {
taskQueue.put(task);
}
boolean tryScheduleTask(Runnable task) {
return taskQueue.add(task);
}
@Override
public void run() {
while (true)
{
try {
Runnable a = taskQueue.take();
if(!(lastTime==-1 || System.currentTimeMillis()-lastTime>timeToWait))
{
//so wait !
synchronized (lastTime)
{
lastTime.wait(timeToWait-(System.currentTimeMillis()-lastTime));
}
}
try{
a.run();
lastTime = System.currentTimeMillis();
}catch (Throwable e)
{
//todo handle e
}
} catch (InterruptedException e) {
break;
}
}
}
}
TaskTimer t = new TaskTimer(2000);
t.start();
t.scheduleTask(new Runnable() {
@Override
public void run() {
System.out.println("1");
}
});
t.tryScheduleTask(new Runnable() {
@Override
public void run() {
System.out.println("2");
}
});
希望我能帮助你 你在使用spring库吗?@Deadpool No.GuiceI不知道反应式编程模型和工具是否适合你的需要。