What is a safe and greater method to execute tasks ( in my case call a function ) in specific time ( in my case every two days ) ?
The function retrieves data from the Web. My target is update the data in app whenever it changes on the webserver.
Thanks, good job!
1- If you don't need to be exact about time, you need to use WorkManager and set periodic work request
https://developer.android.com/topic/libraries/architecture/workmanager
fun CreateWorkRequest()
{
val workManager = WorkManager.getInstance(context)
val duration = 2*24*60*60*1000L //2 days in mili second
val workRequest = PeriodicWorkRequestBuilder<AutoBackUpWorker>(duration, TimeUnit.MILLISECONDS)
.setInitialDelay(duration/2, TimeUnit.MILLISECONDS)
.addTag("diaryBackUpWork")
.build()
workManager.enqueueUniquePeriodicWork("backupwork", ExistingPeriodicWorkPolicy.REPLACE, autoBackUpRequest)
}
Worker Class:
class RequestedWorker(val appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams)
{
override fun doWork()
{
}
}
2- If you need to be exact about time (like at 8pm everyday) you need to use Alarm Manager
3- In your case the best choice is implementing DownloadManager for download request in the doWork() method
Related
I am using Workmanager to execute a task within a time period of minutes but it gets executed for the first time only. From my point of view it should execute every minutes.
I am testing on device while the app is in foreground running and power is on.
Code:
class MainActivity : AppCompatActivity() {
val TAG: String = "MainActivity"
lateinit var workLiveData: LiveData<List<WorkInfo>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initWM()
}
private fun initWM() {
val request = PeriodicWorkRequestBuilder<DemoWorker>(1, TimeUnit.MINUTES)
.addTag(TAG)
.build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(TAG,
ExistingPeriodicWorkPolicy.REPLACE, request)
}
}
DemoWorker:
class DemoWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
val TAG: String = "MainActivity"
override fun doWork(): Result {
Log.d(TAG, "doWork: ")
return try {
Result.success(workDataOf("KEY" to "SUCCESS"))
} catch (e: Exception) {
Result.failure()
}
}
}
A reminder about the “minimal interval”. WorkManager is balancing two different requirements: the application with its WorkRequest, and the Android operating system with its need to limit battery consumption. For this reason, even if all the constraints set on a WorkRequest are satisfied, your Work can still be run with some additional delay.
So you are replacing one work after another. The OS may not have the proper time to execute the work. So the best option will be to try with a 1-hour delay.
You can use a flexInterval.Let’s look at an example. Imagine you want to build a periodic Work request with a 30 minutes period. You can specify a flexInterval, smaller than this period, say a 15 minute flexInterval.
The actual code to build a PeriodicWorkPequest with this parameters is:
val logBuilder = PeriodicWorkRequestBuilder<MyWorker>(
30, TimeUnit.MINUTES,
15, TimeUnit.MINUTES)
The result is that our worker will be executed in the second half of the period (the flexInterval is always positioned at the end of the repetition period):
EDIT (TL;DR)
I didn't realize there was more than one constructor for periodic work requests. The clue to my confusion was in the comments of the accepted answer.
Background
I have a few special cases I am trying to solve for while scheduling work. One of them involves doing work immediately and then creating a periodic work request. I found this in the Android's PeriodicWorkRequest documentation:
This work executes multiple times until it is cancelled, with the first execution happening immediately or as soon as the given Constraints are met.
I figured that this meant work would execute upon creating a request. However, this was not what happened in my test implementation. (For this work there is no need for a CoroutineWorker or network connection constraints but its applicable to my business need so I am testing it)
Starting Worker
object WorkerManager {
private val TAG = "WORKER_MANAGER_TEST"
fun buildWorkRequest(
startingNumber: Int,
context: Context
) {
val constraints =
Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val workRequest = PeriodicWorkRequest.Builder(
PeriodicWorker::class.java,
1,
TimeUnit.HOURS,
15,
TimeUnit.MINUTES
)
.setInputData(
workDataOf(Constants.INPUT_DATA_NUMBER to startingNumber)
)
.addTag(Constants.PERIODIC_WORKER_TAG)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
Constants.PERIODIC_WORKER_NAME,
ExistingPeriodicWorkPolicy.REPLACE,
workRequest
)
Log.d(TAG, "Worker started. Starting number: $startingNumber")
}
}
Worker:
class PeriodicWorker(context: Context, workerParams: WorkerParameters): CoroutineWorker(context,
workerParams
) {
companion object {
var isInit = false
var count: Int = 1
}
override suspend fun doWork(): Result = try {
if (!isInit) {
count = inputData.getInt(Constants.INPUT_DATA_NUMBER, Constants.DEFAULT_DATA_NUMBER)
isInit = true
} else {
count += 1
}
Repository.updateNumber(count)
Result.success()
} catch (exception: Exception) {
Result.failure()
}
}
Repo:
object Repository {
private val TAG = "REPOSITORY_TAG"
private val _number = MutableStateFlow(0)
val number: StateFlow<Int> = _number
suspend fun updateNumber(number: Int) {
Log.d(TAG, "Number updated to: $number")
_number.emit(number)
}
}
ViewModel:
class NumberViewModel : ViewModel() {
private val _count = MutableLiveData(0)
val count: LiveData<Int> = _count
init {
viewModelScope.launch {
Repository.number.collect {
_count.postValue(it)
}
}
}
}
Results
I started a worker with 10 as the starting number.
Logs:
8:45am - Worker started. Starting number: 10
9:37am - Number updated to: 10 // work executed
10:37am - Number updated to: 11 // work executed
11:37am - Number updated to: 12 // work executed
Device Info
OS Version 28 -- Samsung SM-T390
My Conclusion
Constraints -
Cannot be an issue. I had network connection during the above test and that is the only given constraint.
Battery Optimizations -
I am sure that this app was white listed prior to running this test.
So in conclusion it seems that PeriodicWorkRequests DO NOT perform immediate work. The Android documentation should instead say:
This work executes multiple times until it is cancelled, with the first period beginning immediately. The first work execution then happens within the first flex interval given the constraints are met.
Question
Does my conclusion seem reasonable? Is there something I haven't considered?
You are overthinking it. Please dump the JS:
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/debugging
Use adb shell dumpsys jobscheduler
And just check what are the Unsatisfied constraints in the dump:
Required constraints: TIMING_DELAY CONNECTIVITY [0x90000000]
Satisfied constraints: DEVICE_NOT_DOZING BACKGROUND_NOT_RESTRICTED WITHIN_QUOTA [0x3400000]
Unsatisfied constraints: TIMING_DELAY CONNECTIVITY [0x90000000]
Also:
Minimum latency: +1h29m59s687ms
As I understand this constructor:
PeriodicWorkRequest.Builder(Class<? extends ListenableWorker> workerClass,
long repeatInterval, TimeUnit repeatIntervalTimeUnit,
long flexInterval, TimeUnit flexIntervalTimeUnit)
means that your work will be executed inside flexInterval of repeatInterval
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
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
I need to upload file from device to my app. I use WorkManager to do it in background.
After updating library from android.arch.work:work-runtime:1.0.0-alpha04 to androidx.work:work-runtime:2.0.0 something goes wrong.
Method doWork() not calling in my UploadFileTask(workerParams: WorkerParameters) : Worker(Application.getContext(), workerParams)
Here is how I run my uploading:
fun upload(id: String, file: File, params: FileStorage.DocParams?, additionalTag: String): File {
cancelUploadIfWas(file)
fileStorage.save(file, params)
val inputData = Data.Builder().putString(FileTask.PATH_KEY, file.path).build()
val uploadWork = OneTimeWorkRequest.Builder(UploadFileTask::class.java)
.addTag(ID_PREFIX + id)
.addTag(PATH_PREFIX + file.path)
.addTag(UPLOAD_TAG)
.addTag(additionalTag)
.keepResultsForAtLeast(0, TimeUnit.SECONDS)
.setInputData(inputData)
.build()
workManager.enqueue(uploadWork)
file.uploadStatus.onLoading()
file.uploadWork=uploadWork
uploadingFiles.put(ID_PREFIX + id, file)
workManager.getWorkInfoByIdLiveData(uploadWork.id).observe(this, uploadObserver)
return file
}
But my uploadObserver receives State.FAILED exactly after State.ENQUEUED
What I'm doing wrong?
Solved
The trick was in that we have to create out task by this way:
UploadFileTask(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams)
The constructor of our task have to receive exactly two parameters: context: Context and workerParams: WorkerParameters
Explanation:
val downloadWork = OneTimeWorkRequest.Builder(downloadingTask)
.addTag(ID_TAG)
.keepResultsForAtLeast(0, TimeUnit.SECONDS)
.build()
workManager.enqueue(downloadWork)
WorkManager expects to receive downloadWork which was biult with downloadingTask, that has exactly two params in its constructor
Have you tried to check the size of your payload/data that you're sending to your worker?
Sometimes when your data object is too large for the worker limits, the doWork() may not be called.
Or, it could be some exception thrown in your doWork() method without you noticing it, so it's failing to proceed with further code executions.
You can try to:
Remove setInputData() from your upload method
Remove getInputData() from your WorkManager class
Now a Log to your doWork() method to check if it's being called
I would like to use WorkManager to update the DB every 24 hours from midnight.
First, I'm understand that the Workmanager's PeriodicWorkRequest does not specify that the worker should operate at any given time.
So I used OneTimeWorkRequest() to give the delay and then put the PeriodicWorkRequest() in the queue, which runs every 24 hours.
1.Constraints
private fun getConstraints(): Constraints {
return Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
.build()
}
2.OneTimeWorkRequest
fun applyMidnightWorker() {
val onTimeDailyWorker = OneTimeWorkRequest
.Builder(MidnightWorker::class.java)
.setInitialDelay(getDelayTime(), TimeUnit.SECONDS)
.setConstraints(getConstraints())
.build()
val workerContinuation =
workManager.beginUniqueWork(Const.DAILY_WORKER_TAG,
ExistingWorkPolicy.KEEP,
onTimeDailyWorker)
workerContinuation.enqueue()
}
getDelayTime() is
private fun getDelayTime(): Long {
...
return midNightTime - System.currentTimeMillis()
}
3.MidnightWorker Class
class MidnightWorker : Worker() {
override fun doWork(): Result {
DailyWorkerUtil.applyDailyWorker()
return Worker.Result.SUCCESS
}
}
4.PeriodicWorkRequest
fun applyDailyWorker() {
val periodicWorkRequest = PeriodicWorkRequest
.Builder(DailyWorker::class.java, 24, TimeUnit.HOURS)
.addTag(Const.DAILY_WORKER)
.setConstraints(getConstraints()).build()
workManager.enqueue(periodicWorkRequest)
}
And I confirmed that the delayTime passed and the midnightWorker was running.
Of course, It worked normally without any relation to the network.
However, test results showed that the delay time worked regardless of device time. As if it were server time
This is my question.
1. No delay according to device time. I want to know if the delay works as per the server time standard.
2. I wonder if the PeriodicWorkRequest can provide InitialDelay like OneTimeWorkRequest.
you've used TimeUnit.SECONDS with setInitialDelay yet getDelayTime is working with milliseconds.
This maybe the cause of you problems