Javaタイマー
1. タイマー–基本
Timer and TimerTask are java util classes that we use to schedule tasks in a background thread. Basically, TimerTask is the task to perform, and Timer is the scheduler.
2. タスクを1回スケジュールする
2.1. 与えられた遅延の後
タイマーを使用して単一のタスクを実行することから始めましょう。
@Test
public void givenUsingTimer_whenSchedulingTaskOnce_thenCorrect() {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Task performed on: " + new Date() + "n" +
"Thread's name: " + Thread.currentThread().getName());
}
};
Timer timer = new Timer("Timer");
long delay = 1000L;
timer.schedule(task, delay);
}
This performs the task after a certain delay, which we gave as the second parameter of the schedule() method. In the next section, we’ll see how to schedule a task at a given date and time.
Note that if we’re running this as a JUnit test, we should add a Thread.sleep(delay * 2) call to allow the Timer’s thread to run the task before the Junit test stops executing.
2.2. 特定の日時に
Now let’s look at the Timer#schedule(TimerTask, Date) method, which takes a Date instead of a long as its second parameter. This allows us to schedule the task at a certain instant, rather than after a delay.
This time, let’s imagine we have an old legacy database, and we want to migrate its data into a new database with a better schema.
We can create a DatabaseMigrationTask class that will handle this migration:
public class DatabaseMigrationTask extends TimerTask {
private List<String> oldDatabase;
private List<String> newDatabase;
public DatabaseMigrationTask(List<String> oldDatabase, List<String> newDatabase) {
this.oldDatabase = oldDatabase;
this.newDatabase = newDatabase;
}
@Override
public void run() {
newDatabase.addAll(oldDatabase);
}
}
簡単にするために、2つのデータベースをStringのListで表しています。 簡単に言えば、移行は最初のリストのデータを2番目のリストに配置することで構成されます。
この移行を目的の瞬間に実行するには、オーバーロードされたバージョンのschedule()メソッドを使用する必要があります。
List<String> oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill");
List<String> newDatabase = new ArrayList<>();
LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2);
Date twoSecondsLaterAsDate = Date.from(twoSecondsLater.atZone(ZoneId.systemDefault()).toInstant());
new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), twoSecondsLaterAsDate);
As we can see, we give the migration task, as well as the date of execution to the schedule() method.
Then the migration is executed at the time indicated by twoSecondsLater:
while (LocalDateTime.now().isBefore(twoSecondsLater)) {
assertThat(newDatabase).isEmpty();
Thread.sleep(500);
}
assertThat(newDatabase).containsExactlyElementsOf(oldDatabase);
Before that moment, the migration doesn’t occur.
3. 繰り返し可能なタスクをスケジュールする
タスクの単一実行をスケジュールする方法について説明したので、繰り返し可能なタスクを処理する方法を見てみましょう。
Once again, the Timer class offers multiple possibilities. We can set up the repetition to observe either a fixed delay or a fixed rate.
A fixed delay means that the execution will start a period of time after the moment the last execution started, even if it was delayed (therefore being itself delayed).
Let’s say we want to schedule a task every two seconds, with the first execution taking one second and the second one taking two, but being delayed by one second. Then the third execution starts at the fifth second:
0s 1s 2s 3s 5s
|--T1--|
|-----2s-----|--1s--|-----T2-----|
|-----2s-----|--1s--|-----2s-----|--T3--|
一方、固定レートは、前の実行が遅延したかどうかに関係なく、各実行が初期スケジュールを尊重することを意味します。
Let’s reuse our previous example. With a fixed rate, the second task will start after three seconds (because of the delay), but the third one will start after four seconds (respecting the initial schedule of one execution every two seconds):
0s 1s 2s 3s 4s
|--T1--|
|-----2s-----|--1s--|-----T2-----|
|-----2s-----|-----2s-----|--T3--|
Now that we’ve covered these two principles, let’s see how we can use them.
固定遅延スケジューリングを使用するために、 schedule()メソッドのオーバーロードがさらに2つあり、それぞれがミリ秒単位で周期性を示す追加のパラメーターを取ります。
なぜ2つの過負荷? Because there’s still the possibility to start the task at a certain moment or after a certain delay.
As for the fixed-rate scheduling, we have the two scheduleAtFixedRate() methods, which also take the periodicity in milliseconds. Again, we have one method to start the task at a given date and time, and another to start it after a given delay.
It’s also worth mentioning that, if a task takes more time than the period to execute, it delays the whole chain of executions, whether we’re using fixed-delay or fixed-rate.
3.1. 固定遅延あり
Now let’s imagine we want to implement a newsletter system, sending an email to our followers every week. In this case, a repetitive task seems ideal.
So let’s schedule the newsletter every second, which is basically spamming, but as the sending is fake, we’re good to go.
First, we’ll design a NewsletterTask:
public class NewsletterTask extends TimerTask {
@Override
public void run() {
System.out.println("Email sent at: "
+ LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()),
ZoneId.systemDefault()));
}
}
タスクは、実行されるたびに、 TimerTask#scheduledExecutionTime()メソッドを使用して収集したスケジュールされた時刻を出力します。
So what if we want to schedule this task every second in fixed-delay mode? We’ll have to use the overloaded version of schedule() that we mentioned earlier:
new Timer().schedule(new NewsletterTask(), 0, 1000);
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
}
もちろん、私たちはいくつかの出来事についてのみテストを実施します:
Email sent at: 2020-01-01T10:50:30.860
Email sent at: 2020-01-01T10:50:31.860
Email sent at: 2020-01-01T10:50:32.861
Email sent at: 2020-01-01T10:50:33.861
As we can see, there’s at least one second between each execution, but they’re sometimes delayed by a millisecond. This phenomenon is due to our decision to used fixed-delay repetition.
3.2. 固定レートで
Now what if we were to use a fixed-rate repetition? Then we would have to use the scheduledAtFixedRate() method:
new Timer().scheduleAtFixedRate(new NewsletterTask(), 0, 1000);
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
}
This time, executions aren’t delayed by the previous ones:
Email sent at: 2020-01-01T10:55:03.805
Email sent at: 2020-01-01T10:55:04.805
Email sent at: 2020-01-01T10:55:05.805
Email sent at: 2020-01-01T10:55:06.805
3.3. 毎日のタスクをスケジュールする
次に、タスクを1日1回実行しましょう:
@Test
public void givenUsingTimer_whenSchedulingDailyTask_thenCorrect() {
TimerTask repeatedTask = new TimerTask() {
public void run() {
System.out.println("Task performed on " + new Date());
}
};
Timer timer = new Timer("Timer");
long delay = 1000L;
long period = 1000L * 60L * 60L * 24L;
timer.scheduleAtFixedRate(repeatedTask, delay, period);
}
4. タイマーとタイマータスクをキャンセルします
The execution of a task can be canceled in a few ways.
4.1. 実行内のTimerTaskをキャンセルします
The first option is to call the TimerTask.cancel() method inside the run() method’s implementation of the TimerTask itself:
@Test
public void givenUsingTimer_whenCancelingTimerTask_thenCorrect()
throws InterruptedException {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Task performed on " + new Date());
cancel();
}
};
Timer timer = new Timer("Timer");
timer.scheduleAtFixedRate(task, 1000L, 1000L);
Thread.sleep(1000L * 2);
}
4.2. タイマーをキャンセルしてください
Another option is to call the Timer.cancel() method on a Timer object:
@Test
public void givenUsingTimer_whenCancelingTimer_thenCorrect()
throws InterruptedException {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Task performed on " + new Date());
}
};
Timer timer = new Timer("Timer");
timer.scheduleAtFixedRate(task, 1000L, 1000L);
Thread.sleep(1000L * 2);
timer.cancel();
}
4.3. Run内のTimerTaskのスレッドを停止します
We can also stop the thread inside the run method of the task, thus canceling the entire task:
@Test
public void givenUsingTimer_whenStoppingThread_thenTimerTaskIsCancelled()
throws InterruptedException {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Task performed on " + new Date());
// TODO: stop the thread here
}
};
Timer timer = new Timer("Timer");
timer.scheduleAtFixedRate(task, 1000L, 1000L);
Thread.sleep(1000L * 2);
}
Notice the TODO instruction in the run implementation; in order to run this simple example, we’ll need to actually stop the thread.
In a real-world custom thread implementation, stopping the thread should be supported, but in this case, we can ignore the deprecation and use the simple stop API on the Thread class itself.
5. タイマーとExecutorService
We can also make good use of an ExecutorService to schedule timer tasks, instead of using the timer.
これは、指定された間隔で繰り返されるタスクを実行する方法の簡単な例です。
@Test
public void givenUsingExecutorService_whenSchedulingRepeatedTask_thenCorrect()
throws InterruptedException {
TimerTask repeatedTask = new TimerTask() {
public void run() {
System.out.println("Task performed on " + new Date());
}
};
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
long delay = 1000L;
long period = 1000L;
executor.scheduleAtFixedRate(repeatedTask, delay, period, TimeUnit.MILLISECONDS);
Thread.sleep(delay + period * 3);
executor.shutdown();
}
では、TimerソリューションとExecutorServiceソリューションの主な違いは何ですか。
- Timer can be sensitive to changes in the system clock; ScheduledThreadPoolExecutor isn’t.
- Timer has only one execution thread; ScheduledThreadPoolExecutor can be configured with any number of threads.
- Runtime Exceptions thrown inside the TimerTask kill the thread, so the following scheduled tasks won’t run further; with ScheduledThreadExecutor, the current task will be canceled, but the rest will continue to run.
6. 結論
In this article, we illustrated the many ways we can make use of the simple, yet flexible Timer and TimerTask infrastructure built into Java for quickly scheduling tasks. There are, of course, much more complex and complete solutions in the Java world if we need them, such as the Quartz library, but this is a very good place to start.
The implementation of these examples can be found in over on GitHub.