0
0

【Java】備忘録:Timer、TimerTask

Posted at

Day : 2024/2/6


コメント

Java を勉強し始めて 2 日目。
来週までには GUI 操作を実装したい。

今回は、TimerとTimerTask の備忘録。


定期的に関数を実行したいときに使う?

  • 1日 1回スクレイピングする
  • ゲームの画面更新
  • その他いろいろ

以下、コード

// main.java

public class App {
	
	static TimerTest	tTimer;

	public static void main( String[] args ) {
		tTimer	= new TimerTest();
		tTimer.test_schedule();
	}
}

// TunerTest.java

import java.util.Timer;
import java.util.TimerTask;

public class TimerTest extends Timer {

	MyTimerTask tTask;

	TimerTest() {
		tTask	= new MyTimerTask();
	}

	public void test_schedule() {
		// 1 秒後から 1 秒間隔で実行される。
		this.schedule( tTask, 1000, 1000 );
	}


	// 実行内容を記載するクラス?
	private class MyTimerTask extends TimerTask {
		
		int	num_run;	// 実行回数

		// コンストラクタ
		MyTimerTask() {
			num_run	= 0;
		};

        // test_schedule() 内では TimerTask.run() の内容が実行される。
		@Override
		public void run() {
			
			// 実行されたときには num_run をインクリメント
			this.num_run	+= 1;

			// 画面出力
			System.out.println( "run test_schedule : " + this.num_run );

			// num_run が 5 になった時の処理
			if ( this.num_run == 5 ) {
				this.cancel();								// タイマータスクを取り消す。
				System.out.println( "FINISH PROGRAM..." );	// 画面に出力して、
    			System.exit(0);								// プログラムを終了する。
			}
		}
	}
}
	
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0