【问题标题】:How to run a job periodically and within certain duration如何在一定时间内定期运行作业
【发布时间】:2020-03-08 00:44:01
【问题描述】:

由于容器的生命周期设置为 5 小时,因此计划定期运行作业并在一定时间后关闭执行以清理线程。 Java ScheduledExecutorService 提供了定期安排作业的功能,但关闭方法将立即关闭执行程序服务,而不是在一段时间后关闭。有没有办法处理这种情况?任何人都知道在Java中是否有更好的api可以使用?任何建议表示赞赏

【问题讨论】:

  • 这能回答你的问题吗? java ScheduleExecutorService timeout task
  • 如果您在 Google 上搜索“超时时间安排”,您可能会找到答案。
  • 谢谢。我正在搜索“在一定时间内安排执行程序服务”,但没有运气..不知道我怎么没有搜索超时!

标签: java multithreading


【解决方案1】:

为什么不安排 Executor 自行关闭?

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(() -> System.out.println("tick"), 1, 1, TimeUnit.SECONDS);
    exec.scheduleAtFixedRate(exec::shutdown, 5, 1, TimeUnit.SECONDS);

关闭是使用FixedRate 还是FixedDelay 并不重要,因为它只会运行一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    相关资源
    最近更新 更多