简体   繁体   中英

Android schedule job on interval for defined amount of time

I'm wondering is there a possibility in some of the scheduling libraries in Android SDK that can achieve this type of behaviour:

  • Schedule some work (ex. ping network)
  • It is executed every X seconds
  • Executions last for Y minutes

There are some stuff like ScheduledThreadPoolExecutor and some custom solutions, but how could I achieve this with officially approved libraries? Thanks.

Work Manager is the finest option for job scheduling.

  1. One-time request.
val workManager = WorkManager.getInstance(context)
val oneTimeRequest = OneTimeWorkRequest.Builder(BackupFileUploadWorker::class.java)
                .setConstraints(constraints)
                .build() 
workManager.enqueueUniqueWork(BackupFileUploadWorker::class.java.simpleName, ExistingWorkPolicy.REPLACE, oneTimeRequest)
  1. Periodic Request.
var builder : PeriodicWorkRequest.Builder? = null
var periodicWorkRequest : PeriodicWorkRequest? = null

when(backupSettings.backupDuration){
    context.getString(R.string.backup_type_duration_never) -> {
        return
    }
    context.getString(R.string.backup_type_duration_daily) -> {
        builder = PeriodicWorkRequest.Builder(BackupFileUploadWorker::class.java, 1, TimeUnit.DAYS)
    }
    context.getString(R.string.backup_type_duration_weekly) -> {
        builder = PeriodicWorkRequest.Builder(BackupFileUploadWorker::class.java, 7, TimeUnit.DAYS)
    }
    context.getString(R.string.backup_type_duration_monthly) -> {
        builder = PeriodicWorkRequest.Builder(BackupFileUploadWorker::class.java, 30, TimeUnit.DAYS)
    }
}

periodicWorkRequest = builder?.build()
workManager.enqueueUniquePeriodicWork(BackupFileUploadWorker::class.java.simpleName, ExistingPeriodicWorkPolicy.REPLACE, periodicWorkRequest!!)            
          

For more details please refer to official documents by this [Work Manager] ( https://developer.android.com/topic/libraries/architecture/workmanager )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM