Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

kotlin - Schedule task to be executed later (time + date) android

I just search for code that let me do an action after the timer (with specific date and time) finish (in Kotlin) and save it in a list

Like timer for post a tweet on Twitter: https://business.twitter.com/en/help/campaign-editing-and-optimization/scheduled-tweets.html

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use WorkManager for that.

Dependency:

implementation "androidx.work:work-runtime-ktx:2.3.0"

Example:

class LogWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {

    override fun doWork(): Result {
        // Do the work here--in this case, upload the images.
        Log.i("ToastWorker", "doWork: Working ? ? ?")

        // Indicate whether the task finished successfully with the Result
        return Result.success()
    }
}

Then set the delay time

val logWorkRequest = OneTimeWorkRequestBuilder<LogWorker>()
        .setInitialDelay(5, TimeUnit.SECONDS) // here you can set the delay time in Minutes, Hours
        .build()

Start the timer

WorkManager.getInstance(this).enqueue(toastWorkRequest)

Here is a Codelab for more insight. You can also read more here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...