株式会社イーブ|未経験・転職の方も就職可能。Javaプログラマー育成のエキスパート

HOMEJAVA技術者育成システム開発求人情報個人情報保護

第 47 回 ~ マルチスレッド編 ScheduledExecutorServiceインターフェース ~

トップページ > Java技術者育成 > Javaワンポイント > 第 47 回 ~ マルチスレッド編 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日間隔で実行されるようにしています。


[Javaワンポイント]内の前後の記事
第 48 回 ~ マルチスレッド編 CompletionServiceインターフェース ~
→ 第 47 回 ~ マルチスレッド編 ScheduledExecutorServiceインターフェース ~
第 46 回 ~ マルチスレッド編 ExecutorServiceインターフェース ~


■更新日時での前後の記事
4月15日 お天気
→ 第 47 回 ~ マルチスレッド編 ScheduledExecutorServiceインターフェース ~
受付より vol.44