Search code examples
javaandroidkotlinschedule

How to implement a time scheduler in Kotlin


So I want my app to perform an operation at certain intervals of time. After doing a little research I found the some answers on stackoverflow and it led me to this link to something called fixedRateTimer: Heres the first example in that page

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

    try {
   Thread.sleep(1000)
   } 

   finally {
   fixedRateTimer.cancel();
   }

When I added that snippet of code I get an error.

"Expression 'fixedRateTimer' cannot be invoked as a function. The function 'invoke()' is not found Variable 'fixedRateTimer' must be initialized"

I did more research and imported kotlin.concurrent.schedule* and kotlin.concurrent.fixedRateTimer and added a block of code on top of the first to initilize it.

enter image description here

So it fixed the first block code but the one I just added gave me more errors. It stated the function needed to be abstract. So i made it abstract but then an error appeared at the bottom of crossinline stating that the function needs to be inline and not abstract.

So im going crazy because all the code blocks I took are from the documentations so im not sure why im getting these errors. As a beginner Im trying to follow the documentation but im always at a lost at every turn. There were some other answers on that Stackoverflow page I linked like Handlers and schedules but I was still getting similiar type of errors.

So how do I use schedule or fixedRateTimer ? I would appreciate a step-by-step example so I could a get fully understanding of what im typing

Thanks!


Solution

  • Option 1 : use this link :-

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

    Now, since you want to do a periodic task, you have to use,

    Periodic Work request instead of OneTimeWorkRequest and you can set the interval here.

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

    Follow this example :-

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

    Note :-Use of WorkManager API cannly be done if minimum API that you are targetting your app is Android 5.0

    option 2 :

       new CountDownTimer(30000, 1000) {
    
     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }
    
     public void onFinish() {
         mTextField.setText("done!");
     }
    

    }.start();