如何在 Kotlin 中实现时间调度器

How to implement a time scheduler in Kotlin

所以我希望我的应用程序以特定的时间间隔执行操作。在做了一些研究后,我在 and it led me to this link to something called fixedRateTimer 上找到了一些答案:这是该页面中的第一个示例

    val fixedRateTimer = fixedRateTimer(name = "hello-timer",
    initialDelay = 100, period = 100) {
    println("hello world!")}

    try {
   Thread.sleep(1000)
   } 

   finally {
   fixedRateTimer.cancel();
   }

当我添加该代码片段时出现错误。

"表达式 'fixedRateTimer' 不能作为函数调用。找不到函数 'invoke()' 必须初始化变量 'fixedRateTimer'"

我做了更多 research 并导入了 kotlin.concurrent.schedule* 和 kotlin.concurrent.fixedRateTimer 并在第一个代码之上添加了一段代码以进行初始化它。

所以它修复了第一个块代码,但我刚刚添加的那个给了我更多的错误。它说明了需要抽象的功能。所以我把它抽象了,但随后在 crossinline 的底部出现了一个错误,指出该函数需要内联而不是抽象。

所以我快疯了,因为我使用的所有代码块都来自文档,所以我不确定为什么会出现这些错误。作为一个初学者,我试图按照文档进行操作,但我总是在每一个转弯处都不知所措。在我链接的 Whosebug 页面上还有一些其他答案,例如处理程序和时间表,但我仍然遇到类似类型的错误。

那么我该如何使用 schedule 或 fixedRateTimer 呢?我会很感激一个循序渐进的例子,这样我就可以完全理解我输入的内容

谢谢!

选项 1: 使用这个 link :-

https://developer.android.com/topic/libraries/architecture/workmanager/basics

现在既然要做周期性任务,就得用,

Periodic Work request 而不是 OneTimeWorkRequest,您可以在此处设置时间间隔。

 PeriodicWorkRequest saveRequest =
   new PeriodicWorkRequest.Builder(SaveImageToFileWorker.class, 1, TimeUnit.HOURS)
       // Constraints
       .build();

按照这个例子:-

https://developer.android.com/topic/libraries/architecture/workmanager/how-to/define-work

注意:-如果您的应用程序的目标最低 API 是 Android 5.0

,则无法使用 WorkManager API

选项 2:

   new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 }

 public void onFinish() {
     mTextField.setText("done!");
 }

}.start();