ZBLOG

import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledTask { public static void main(String[] args) { ScheduledExecutorService schedule...

如果在启动程序后没有任何输出,可能是因为 ScheduledExecutorService 的线程没有被保持活跃,或者主线程在执行完后直接退出。你可以通过以下方法确保程序持续运行并能够看到输出。

方法1:让主线程休眠

在主方法中添加一个持续运行的机制,比如让主线程休眠一段时间或使用 CountDownLatch 等来保持应用存活。示例代码如下:

  1. import java.util.concurrent.Executors;
  2. import java.util.concurrent.ScheduledExecutorService;
  3. import java.util.concurrent.TimeUnit;
  4. public class ScheduledTask {
  5. public static void main(String[] args) {
  6. ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  7. Runnable task = () -> {
  8. // 调用你的接口逻辑,例如使用HttpClient等发送请求。
  9. System.out.println("Calling API... " + System.currentTimeMillis());
  10. };
  11. // 每隔5秒执行一次
  12. scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
  13. // 保持主线程活着,以便调度器可以继续工作
  14. try {
  15. Thread.sleep(30000); // 主线程睡眠30秒
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. // 关闭调度器
  20. scheduler.shutdown();
  21. }
  22. }

方法2:使用 CountDownLatch

另外一种方式是利用 CountDownLatch 来使得主线程等待直到某个条件满足,比如任务完成:

  1. import java.util.concurrent.CountDownLatch;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.ScheduledExecutorService;
  4. import java.util.concurrent.TimeUnit;
  5. public class ScheduledTask {
  6. public static void main(String[] args) throws InterruptedException {
  7. ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  8. Runnable task = () -> {
  9. System.out.println("Calling API... " + System.currentTimeMillis());
  10. };
  11. // 每隔5秒执行一次
  12. scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
  13. CountDownLatch latch = new CountDownLatch(1);
  14. // 等待用户按下回车键,然后关闭调度器
  15. System.out.println("Press ENTER to stop...");
  16. System.in.read();
  17. latch.countDown(); // Count down the latch
  18. scheduler.shutdown(); // Shut down the scheduler
  19. }
  20. }

总结

无论你选择哪种方式,都能保证程序不会立即退出,从而使得调度任务能够按预期定时执行。在这两种情况下,你应该会每隔5秒看到输出“Calling API…”及当前时间戳。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=20683

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?