gpt4 book ai didi

java - 如何安排任务以定期间隔运行?

转载 作者:IT老高 更新时间:2023-10-28 11:51:44 25 4
gpt4 key购买 nike

我正在尝试一些代码来实现计划任务并想出了这些代码。

import java.util.*;

class Task extends TimerTask {


int count = 1;

// run is a abstract method that defines task performed at scheduled time.
public void run() {
System.out.println(count+" : Mahendra Singh");
count++;
}
}

class TaskScheduling {

public static void main(String[] args) {
Timer timer = new Timer();


// Schedule to run after every 3 second(3000 millisecond)
timer.schedule( new Task(), 3000);
}
}

我的输出:

1  :  Mahendra Singh

我希望编译器以 3 秒的周期间隔打印一系列 Mahendra Singh,但尽管等待了大约 15 分钟,但我只得到一个输出...我该如何解决这个问题?

最佳答案

ScheduledExecutorService 优于 Timer

我希望为您提供 Timer 的替代方法,使用 - ScheduledThreadPoolExecutor , ScheduledExecutorService 的实现界面。根据“Java in Concurrency”,它比 Timer 类有一些优势:

A Timer creates only a single thread for executing timer tasks. If a timer task takes too long to run, the timing accuracy of other TimerTask can suffer. If a recurring TimerTask is scheduled to run every 10 ms and another Timer-Task takes 40 ms to run, the recurring task either (depending on whether it was scheduled at fixed rate or fixed delay) gets called four times in rapid succession after the long-running task completes, or "misses" four invocations completely. Scheduled thread pools address this limitation by letting you provide multiple threads for executing deferred and periodic tasks.

Timer 的另一个问题是,如果 TimerTask 抛出未经检查的异常,它的行为会很差。也称为“线程泄漏”

The Timer thread doesn't catch the exception, so an unchecked exception thrown from a TimerTask terminates the timer thread. Timer also doesn't resurrect the thread in this situation; instead, it erroneously assumes the entire Timer was cancelled. In this case, TimerTasks that are already scheduled but not yet executed are never run, and new tasks cannot be scheduled.

另外一个建议是,如果您需要构建自己的调度服务,您仍然可以通过使用 DelayQueue 来利用该库,这是一个 BlockingQueue 实现提供ScheduledThreadPoolExecutor的调度功能。 DelayQueue 管理延迟对象的集合。 Delayed 有一个与之关联的延迟时间:DelayQueue 允许您仅在延迟已过期时获取元素。对象从 DelayQueue 中返回,该 DelayQueue 按与其延迟相关的时间排序。

关于java - 如何安排任务以定期间隔运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4544197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com