Avoid paralel run of RestartWorker

Make doWork synchronized
Do not add failures count from the worker
This commit is contained in:
sim 2024-10-28 11:12:10 +00:00
parent f17c932e9f
commit b3c28be0fc
2 changed files with 27 additions and 25 deletions

View File

@ -77,15 +77,6 @@ object FailureHandler {
this.eventSource.getAndSet(null)?.cancel()
}
fun setMaxFails(context: Context) {
// We set nFails to max to not restart the worker
// and keep it running
nFails.set(5)
ttlFails.getAndIncrement()
this.eventSource.getAndSet(null)?.cancel()
DisconnectedNotification(context).showSingle()
}
fun clearFails() {
ttlFails.set(0)
nFails.set(0)

View File

@ -14,31 +14,42 @@ private const val UNIQUE_ONETIME_WORK_TAG = "nextpush::RestartWorker::unique_one
class RestartWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
/**
* Restart the service if we have never received an event, or haven't received an event
* in the expected time
*/
override fun doWork(): Result {
Log.d(TAG, "Working")
if (!AppCompanion.hasInternet.get()) {
Log.d(TAG, "Aborting, no internet.")
return Result.success()
}
val currentDate = Calendar.getInstance()
val restartDate = Calendar.getInstance()
AppCompanion.lastEventDate?.let {
restartDate.time = it.time
restartDate.add(Calendar.SECOND, AppCompanion.keepalive.get())
Log.d(TAG, "restartDate: ${restartDate.time}")
if (currentDate.after(restartDate)) {
// We avoid running twice at the same time
synchronized(lock) {
Log.d(TAG, "Working")
if (!AppCompanion.hasInternet.get()) {
Log.d(TAG, "Aborting, no internet.")
return Result.success()
}
val currentDate = Calendar.getInstance()
val restartDate = Calendar.getInstance()
AppCompanion.lastEventDate?.let {
// We check that the last received event isn't older than the keep alive
restartDate.time = it.time
restartDate.add(Calendar.SECOND, AppCompanion.keepalive.get())
Log.d(TAG, "restartDate: ${restartDate.time}")
if (currentDate.after(restartDate)) {
Log.d(TAG, "We should have received an event before ${restartDate.time}. Restarting")
/** We do not update [FailureHandler]'s counter, it will be done by the next requests. */
StartService.startListener(applicationContext)
}
} ?: run {
Log.d(TAG, "Restarting")
FailureHandler.setMaxFails(applicationContext) // Max, will keep using the current worker
StartService.startListener(applicationContext)
}
} ?: run {
Log.d(TAG, "Restarting")
StartService.startListener(applicationContext)
// We consider this run as the first event
AppCompanion.lastEventDate = currentDate
}
return Result.success()
}
companion object {
private val lock = Object()
fun startPeriodic(context: Context) {
getAccount(context) ?: return