【问题标题】:Creating a Scheduler(Timer) inside run method of a Scheduler(Timer)在 Scheduler(Timer) 的 run 方法中创建 Scheduler(Timer)
【发布时间】:2013-06-28 10:38:12
【问题描述】:

参考Java Timer ClassScheduledExecutorService interface,我可以在执行线程(其他调度器)的run方法(或TimerTask)中设置调度器(或定时器)吗?

案例研究: 我有一个包含歌曲列表(10,000 首)和播放歌曲的时间安排的数据库。

所以我想创建一个调度程序(比如 1 个)(周期为 1 小时),它将搜索数据库并为计划在一小时内播放的所有歌曲创建调度程序。

一小时后 scheduler1 将删除所有线程并再次搜索数据库并为其他线程创建调度程序。

这是个好主意吗?可以创建吗?

或者我应该一次创建 10000 个调度器?

在这种情况下,哪个是更好的计时器或调度器?

【问题讨论】:

    标签: java timer scheduledexecutorservice


    【解决方案1】:

    为什么不直接打电话给ScheduledExecutorService.scheduleAtFixedRateScheduledExecutorService.scheduleWithFixedDelay

    更新

    这是实现(我相信)您想要的一种方式:

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    
    void start(final Connection conn)
    {
      executor.scheduleWithFixedDelay(new Runnable(){ public void run(){ try { poll(conn); } catch (Exception e) { e.printStackTrace(); } } }, 0, 1, TimeUnit.HOURS);
    }
    
    private void poll(Connection conn) throws SQLException
    {
      final ResultSet results = conn.createStatement().executeQuery("SELECT song, playtime FROM schedule WHERE playtime > GETDATE() AND playtime < GETDATE() + 1 HOUR");
      while (results.next())
      {
        final String song = results.getString("song");
        final Time time = results.getTime("playtime");
    
        executor.schedule(new Runnable(){ public void run() { play(song); } }, time.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
      }
    }
    

    【讨论】:

    • Hii.Yeah 但是我必须一次创建 10000 个调度程序(性能问题?)。此外,我的数据库不断更新,因此每 1 小时轮询一次数据库,然后在那 1 小时内安排所有歌曲是什么我想要。这可能吗?
    • @user2511713,为什么每首歌曲需要一个调度程序?
    • 谢谢,这就是我想要的。:-)
    猜你喜欢
    • 2020-07-16
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    相关资源
    最近更新 更多