当前位置:网站首页>Learning II of workmanager
Learning II of workmanager
2022-07-05 10:16:00 【Mr_ Tony】
List of articles
One 、 Preface
Work
There are several states during operation . At run time , State
It also changes . When the task begins , Status is ENQUEUED
. Run time transition to RUNNING
, At the end of the run, it will become SUCCEEDED
、FAILED
. If you try again , The state will return to ENQUEUED
. If you cancel the work , The state will become CANCELLED
.
SUCCEEDED
、FAILED
and CANCELLED
All indicate the termination status of this work . If your work is in any of the above states ,WorkInfo.State.isFinished()
Will return to true.
The following is the flow chart of task execution
The above is a one-time task execution process . If it's a timed mission , Then there won't be SUCCEEDED
、FAILED
state . The following is the flow chart of scheduled tasks .
Two 、 Only job
Generally speaking, the following methods can be used to start work
WorkManager
.getInstance(this)
.enqueue(uploadWorkRequest)
But if we inadvertently write the code twice , Then the task will be performed twice ( Although this should not appear ). To avoid this problem , Officials provide the only way to ensure the execution of one-time tasks and scheduled tasks respectively .
WorkManager.enqueueUniqueWork()
( For one-time work )WorkManager.enqueueUniquePeriodicWork()
( For regular work )
Both methods accept 3 Parameters :
- uniqueWorkName - Used to uniquely identify a work request
String
. - existingWorkPolicy - this
enum
You can tell WorkManager: If there is a unique work chain with that name that has not yet been completed , What should be done . For details , see also Conflict resolution policy . - work - To schedule
WorkRequest
.
The reference codes are as follows :
val sendLogsWorkRequest =
PeriodicWorkRequestBuilder<SendLogsWorker>(24, TimeUnit.HOURS)
.setConstraints(Constraints.Builder()
.setRequiresCharging(true)
.build()
)
.build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"sendLogs",
ExistingPeriodicWorkPolicy.KEEP,
sendLogsWorkRequest
)
3、 ... and 、 Conflict strategy
Please refer to the official website below
When scheduling only work , You must inform WorkManager A conflict occurs when an operation is to be performed . You can do this by passing an enumeration when you add work to the queue .
For one-time work , You need to provide a
ExistingWorkPolicy
, It supports... For handling conflicts 4 An option .
REPLACE
: Replace an existing job with a new one . This option will cancel the existing work .KEEP
: Keep your current job , And ignore new jobs .APPEND
: Attach new work to the end of existing work . This policy will lead to your new job link To existing work , After the existing work is completed .Existing jobs will be a prerequisite for new jobs . If the current job becomes
CANCELLED
orFAILED
state , New jobs will also becomeCANCELLED
orFAILED
. If you want to run a new job regardless of the state of your existing job , Please switch toAPPEND_OR_REPLACE
.
APPEND_OR_REPLACE
The function is similar toAPPEND
, But it doesn't depend on precondition Working state . Even if the existing work becomesCANCELLED
orFAILED
state , The new job will still work .For regular work , You need to provide a
ExistingPeriodicWorkPolicy
, It supportsREPLACE
andKEEP
These two options . The functions of these options correspond to ExistingWorkPolicy Function the same .
Four 、 Observe the state of work
When the work starts , The corresponding work information can be obtained in the following ways .
// by id
workManager.getWorkInfoById(syncWorker.id) // ListenableFuture<WorkInfo>
// by name
workManager.getWorkInfosForUniqueWork("sync") // ListenableFuture<List<WorkInfo>>
// by tag
workManager.getWorkInfosByTag("syncTag") // ListenableFuture<List<WorkInfo>>
The assignment methods corresponding to the above three acquisition methods are as follows :
// by id
val uploadWorkRequest: OneTimeWorkRequest = OneTimeWorkRequest.from(WorkTest::class.java)// Simple way
val workerId = uploadWorkRequest.id
//by name
WorkManager
.getInstance(this)
.enqueueUniqueWork("workName",
ExistingWorkPolicy.KEEP,
uploadWorkRequest)
//by tag
val uploadWorkRequest: WorkRequest = // Complex builder approach
OneTimeWorkRequestBuilder<WorkTest>()
.addTag("first")
.build()
The query returns
WorkInfo
Object'sListenableFuture
, This value contains the of the workid
、 Its mark 、 Its currentState
And byResult.success(outputData)
Any output data set .Using each method
LiveData
variant , You can observe by registering listenersWorkInfo
The change of ( It should be noted that the name of the called function is getWorkInfoByIdLiveData instead of getWorkInfoById()). for example , If you want to display a message to the user after a job is successfully completed , You can make the following settings :workManager.getWorkInfoByIdLiveData(syncWorker.id) .observe(viewLifecycleOwner) { workInfo -> if(workInfo?.state == WorkInfo.State.SUCCEEDED) { Snackbar.make(requireView(), R.string.work_completed, Snackbar.LENGTH_SHORT) .show() } }
5、 ... and 、 Complex query
WorkManager 2.4.0 And later versions support the use of
WorkQuery
Object to perform complex queries on the jobs that have been queued .WorkQuery Supports tags by work 、 A combination of status and unique work name .The following example shows how to find a with “syncTag” Mark 、 be in
FAILED
orCANCELLED
state , And the unique job name is “preProcess” or “sync” All work of .val workQuery = WorkQuery.Builder .fromTags(listOf("syncTag")) .addStates(listOf(WorkInfo.State.FAILED, WorkInfo.State.CANCELLED)) .addUniqueWorkNames(listOf("preProcess", "sync")) .build() val workInfos: ListenableFuture<List<WorkInfo>> = workManager.getWorkInfos(workQuery)
WorkQuery
Every component in ( Mark 、 Status or name ) And other components areAND
logical relationship . Every value in the component isOR
logical relationship . for example :(name1 OR name2 OR ...) AND (tag1 OR tag2 OR ...) AND (state1 OR state2 OR ...)
.
WorkQuery
It also applies to equivalent LiveData MethodgetWorkInfosLiveData()
.
6、 ... and 、 Cancel and stop work
Sometimes tasks need to be cancelled , You can use the following
// by id
workManager.cancelWorkById(syncWorker.id)
// by name
workManager.cancelUniqueWork("sync")
// by tag
workManager.cancelAllWorkByTag("syncTag")
WorkManager Will check the work in the background
State
. If the work has complete , The system doesn't do anything . otherwise , The status of the work will change toCANCELLED
, Then it won't run . whatever Rely on this work OfWorkRequest
The assignment will also becomeCANCELLED
.at present ,
RUNNING
May receive a reply toListenableWorker.onStopped()
Call to . If any cleaning operation is required , Please replace this method . For details , see also Stop the running worker .
So after the task stops , Can be rewritten in onStopped()
Function to handle the closing work . It can also be done through ListenableWorker.isStopped()
Come and see if the task of wiping sweat stops , Examples are as follows :
class WorkTest(val appContext: Context, workerParams: WorkerParameters): Worker(appContext, workerParams) {
override fun doWork(): Result {
if(isStopped){
return Result.success()
}
return Result.success()
}
}
7、 ... and 、 Reference link
边栏推荐
- Cerebral Cortex:有向脑连接识别帕金森病中广泛存在的功能网络异常
- 如何獲取GC(垃圾回收器)的STW(暫停)時間?
- Energy momentum: how to achieve carbon neutralization in the power industry?
- The king of pirated Dall · e? 50000 images per day, crowded hugging face server, and openai ordered to change its name
- ArcGIS Pro 创建要素
- Coffeescript Chinese character to pinyin code
- 程序员如何活成自己喜欢的模样?
- 《剑来》语句摘录(七)
- 能源势动:电力行业的碳中和该如何实现?
- ConstraintLayout官方提供圆角ImageFilterView
猜你喜欢
Detailed explanation of the use of staticlayout
Six simple cases of QT
学习笔记6--卫星定位技术(上)
Universal double button or single button pop-up
自动化规范检查软件如何发展而来?
字节跳动面试官:一张图片占据的内存大小是如何计算
QT timer realizes dynamic display of pictures
@SerializedName注解使用
Mysql80 service does not start
Hard core, have you ever seen robots play "escape from the secret room"? (code attached)
随机推荐
善用兵者,藏于无形,90 分钟深度讲解最佳推广价值作品
Openes version query
Livedata interview question bank and answers -- 7 consecutive questions in livedata interview~
Glide advanced level
Glide conclusion
Swift uses userdefaults and codable to save an array of class objects or structure instances
Cerebral cortex: directed brain connection recognition widespread functional network abnormalities in Parkinson's disease
The most complete is an I2C summary
Energy momentum: how to achieve carbon neutralization in the power industry?
QT VT100 parser
Redis如何实现多可用区?
Those who are good at using soldiers, hide in the invisible, and explain the best promotional value works in depth in 90 minutes
ArcGIS Pro 创建要素
Unity粒子特效系列-毒液喷射预制体做好了,unitypackage包直接用 - 上
Cent7 Oracle database installation error
[system design] index monitoring and alarm system
自动化规范检查软件如何发展而来?
【小技巧】獲取matlab中cdfplot函數的x軸,y軸的數值
面试:List 如何根据对象的属性去重?
历史上的今天:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生...