0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Kotlin: Timer() の使い方

Posted at

プログラム

MainActivity.kt
package com.example.timer01

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import java.util.*

class MainActivity : AppCompatActivity() {
    val timer = Timer()
    private val timerTask = Task()
    private val delay: Long = 0L
    private val interval: Long = 2000L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // activity_mainのレイアウトを使用

        timer.scheduleAtFixedRate(timerTask, delay, interval)
    }

    class Task : TimerTask() {
        var count = 0
        override fun run() {
            println("count = " + count)
            count += 1
        }
    }

    override fun onStop() {
        super.onStop()
        timer.cancel()
    }
}

実行結果

13:12:59.468  I  count = 3
13:13:01.468  I  count = 4
13:13:03.468  I  count = 5
13:13:05.469  I  count = 6
13:13:07.468  I  count = 7
13:13:09.469  I  count = 8
13:13:11.468  I  count = 9
13:13:13.468  I  count = 10
13:13:15.468  I  count = 11
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?