gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:01 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的替代方案,使用 - ScheduledThreadPoolExecutorScheduledExecutorService 的实现界面。根据“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 来利用该库,这是一个提供 ScheduledThreadPoolExecutor 调度功能的 BlockingQueue 实现。 DelayQueue 管理 Delayed 对象的集合。 Delayed 具有与其关联的延迟时间:DelayQueue 允许您仅在延迟已过时才获取元素。对象从 DelayQueue 返回,按与其延迟相关的时间排序。

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

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