第48回 マルチスレッド編ScheduledExecutorServiceインターフェース
今回のテーマは「ScheduledExecutorService」です。
前回はExecutorServiceを使用してマルチスレッドプログラムを作成しました。 今回は特定の時間に実行するプログラムを作成してみたいと思います。 そのためには、ExecutorServiceインターフェースのサブインターフェースであるScheduledExecutorServiceインターフェースを使用します。 ScheduledExecutorServiceもExecutorsクラスのファクトリメソッドを使用して取得することができます。 newScheduledThreadPoolメソッドやnewSingleThreadScheduledExecutorメソッドは一般的に使用される構成で設定されたScheduledExecutorServiceを返してくれます。
次のサンプルコードは目覚まし時計プログラムです。(J2SE6.0以上対応)
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("input.wav");
long initialDelay = getAlarmTimeMillis(7, 0, 0)
- System.currentTimeMillis();
long period = TimeUnit.DAYS.toMillis(1);
ScheduledExecutorService scheduledExecutorService
= Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(new IRunnable(file),
initialDelay, period, TimeUnit.MILLISECONDS);
}
public static long getAlarmTimeMillis(int hour, int minute, int second) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
if (new Date().after(calendar.getTime())) {
calendar.add(Calendar.DAY_OF_WEEK, 1);
}
return calendar.getTimeInMillis();
}
}
class IRunnable implements Runnable {
private File file;
public IRunnable(File file) {
this.file = file;
}
public void run() {
System.out.println(new Date());
try {
AudioInputStream audioInputStream
= AudioSystem.getAudioInputStream(file);
byte[] bytes = new byte[audioInputStream.available()];
AudioFormat audioFormat = audioInputStream.getFormat();
audioInputStream.read(bytes);
audioInputStream.close();
SourceDataLine sourceDataLine
= AudioSystem.getSourceDataLine(audioFormat);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
sourceDataLine.write(bytes, 0, bytes.length);
sourceDataLine.drain();
sourceDataLine.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
IRunnableは時間を表示し、アラームを鳴らすタスクです。
scheduleAtFixedRateメソッドは初期遅延時間の経過後にタスクを実行し、その後は一定期間ごとにタスクを実行します。
サンプルコードは午前7時までの時間を初期遅延時間とし、その後は1日間隔で実行されるようにしています。

