这是一个非常有意义的想法——将复杂的任务限制在一定的执行时间。在实际的网络计算中,当复杂的搜索任务的持续时间超过最大可接受的时间时,许多用户将不愿意等待它完成。
Enterprise 容器控制线程池,以及活动线程之间的 CPU 资源分配。它还考虑了耗时的 I/O 任务(通常是磁盘访问)期间的保留时间。
尽管如此,对启动任务变量进行编程是有意义的,因此在复杂任务期间不时验证该特定任务的持续时间。我建议您编写一个本地的、可运行的任务,该任务从作业队列中选择计划任务。我在 Glassfish 下运行的 Java Enterprise 后端应用程序有这方面的经验。
首先是接口定义Duration.java
// Duration.java
@Qualifier
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Duration {
public int minutes() default 0; // Default, extended from class, within path
}
现在遵循作业的定义TimelyJob.java
// TimelyJob.java
@Duration(minutes = 5)
public class TimelyJob {
private LocalDateTime localDateTime = LocalDateTime.now();
private UUID uniqueTaskIdentifier;
private String uniqueOwnerId;
public TimelyJob(UUID uniqueTaskIdentifier, String uniqueOwnerId) {
this.uniqueTaskIdentifier = uniqueTaskIdentifier;
this.uniqueOwnerId = uniqueOwnerId;
}
public void processUntilMins() {
final int minutes = this.getClass().getAnnotation(Duration.class).minutes();
while (true) {
// do some heavy Java-task for a time unit, then pause, and check total time
// break - when finished
if (minutes > 0 && localDateTime.plusMinutes(minutes).isAfter(LocalDateTime.now())) {
break;
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.err.print(e);
}
}
// store result data in result class, 'synchronized' access
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public UUID getUniqueTaskIdentifier() {
return uniqueTaskIdentifier;
}
public String getUniqueOwnerId() {
return uniqueOwnerId;
}
}
执行定时作业的 Runnable 任务 - TimedTask.java - 实现如下:
// TimedTask.java
public class TimedTask implements Runnable {
private LinkedBlockingQueue<TimelyJob> jobQueue = new LinkedBlockingQueue<TimelyJob>();
public void setJobQueue(TimelyJob job) {
this.jobQueue.add(job);
}
@Override
public void run() {
while (true) {
try {
TimelyJob nextJob = jobQueue.take();
nextJob.processUntilMins();
Thread.sleep(100);
} catch (InterruptedException e) {
System.err.print(e);
}
}
}
}
在单独的代码中,TimedTask 的注视
public void initJobQueue() {
new Thread(new TimedTask()).start();
}
这个功能实际上是在 Java 中实现了一个批处理作业调度器,使用注解来控制结束任务的时间限制。