简体   繁体   English

在Scheduler(Timer)的run方法内创建Scheduler(Timer)

[英]Creating a Scheduler(Timer) inside run method of a Scheduler(Timer)

With reference to Java Timer Class or ScheduledExecutorService interface ,Can I set a scheduler(or timer) inside run method (or TimerTask) of the executor thread(other scheduler)? 参考Java Timer ClassScheduledExecutorService接口 ,是否可以在执行程序线程(其他调度程序)的运行方法(或TimerTask)内设置调度程序(或计时器)?

Case Study: I have a database containing a list of songs(10,000) and schedule time to play the song. 案例研究:我有一个数据库,其中包含歌曲列表(10,000)和安排播放歌曲的时间。

So I thought of creating a scheduler(say 1)(of period 1 hour) which will search the database and create scheduler for all songs which are scheduled to be played within one hour. 因此,我想到了创建一个调度程序(例如1)(周期为1小时),该程序将搜索数据库并为所有计划在一小时内播放的歌曲创建调度程序。

After one hour the scheduler1 will delete all the threads and again search the database and create scheduler for other threads. 一小时后,scheduler1将删除所有线程,然后再次搜索数据库并为其他线程创建调度程序。

Is it a good idea?Possible to create? 这是一个好主意吗?可以创造吗?

Or should I create 10000 scheduler at once? 还是应该一次创建10000个调度程序?

In this case which one will be better timer or scheduler? 在这种情况下,哪种计时器或调度程序会更好?

Why not just call ScheduledExecutorService.scheduleAtFixedRate or ScheduledExecutorService.scheduleWithFixedDelay ? 为什么不只调用ScheduledExecutorService.scheduleAtFixedRateScheduledExecutorService.scheduleWithFixedDelay

UPDATE UPDATE

This is one means of implementing what (I believe) you want: 这是实现您想要的(我相信)的一种方法:

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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM