문제

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)?

Case Study: I have a database containing a list of songs(10,000) and schedule time to play the song.

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.

After one hour the scheduler1 will delete all the threads and again search the database and create scheduler for other threads.

Is it a good idea?Possible to create?

Or should I create 10000 scheduler at once?

In this case which one will be better timer or scheduler?

도움이 되었습니까?

해결책

Why not just call ScheduledExecutorService.scheduleAtFixedRate or ScheduledExecutorService.scheduleWithFixedDelay?

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top