LoginSignup
2
0

More than 3 years have passed since last update.

KotlinのCoroutineをコマンドラインで実行してみた

Last updated at Posted at 2018-11-12

gradleをインストールするためにSDKManagerをインストールします。
あ、あとKotlinはbrewでインストールしました。
CoroutineはKotlin1.3.0から正式にリリースされてます。

command
// Kotlinインストール
$ brew install kotlin

// SDKManagerのインストール
$ curl -s get.sdkman.io | bash

// SDKManagerを環境変数に登録(デフォルトディレクトリ上)
$ source .sdkman/bin/sdkman-init.sh

// sdkコマンドが通ったら
$ sdk install gradle

// gradleプロジェクト用のディレクトリを作成します。
$ mkdir CoroutineTest
$ cd CoroutineTest

// gradleプロジェクトを初期化します。
$ gradle init

これでbuild.gradleが出来上がるので以下のように編集

buid.gradle
plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.3.0'
}

repositories {
    jcenter()
    //mavenCentral()
}

dependencies {
    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.0'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1"
}
apply plugin: 'kotlin'

kotlin {
    experimental {
        coroutines 'enable'
    }   
}

apply plugin: 'application'

// クラス名に書き換えてください
mainClassName = "KotlinCmdMain"

あとはmainを持つKotlinCmdMainクラス(これも自分で作成した名前で)を
プロジェクトからsrc/main/kotlinディレクトリを作ってそこに置く。

KotlinCmdMain.kt
// これは誰かのを参考にした、気がする。思い出したら元記事を記載します。
import kotlinx.coroutines.runBlocking                                                                                                                                              
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class KotlinCmdMain {
    companion object {
        @JvmStatic
         fun main(args: Array<String>) = runBlocking<Unit> {
            GlobalScope.launch {
                repeat(1000) { i ->
                    println("I'm sleeping $i ...")
                    delay(500L)
                }   
            }   
            delay(1300L) // 遅れて終了する
        }   
    }   
}

ここまでくればあとは実行。

command
// プロジェクトルートで
$ ./gradlew run

結果はこんな感じに出るかと

command
Task :run
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...

BUILD SUCCESSFUL in 2s
2 actionable tasks: 1 executed, 1 up-to-date
2
0
2

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
2
0