Android的工人执行作业多次(Android Worker execute the job mu

2019-09-30 01:30发布

我使用下面的代码调度后台作业执行每15分钟。

WorkManager workManager = WorkManager.getInstance();
PeriodicWorkRequest ulpBackup;

ulpBackup = new PeriodicWorkRequest
    .Builder(Ulp.class, 15, TimeUnit.MINUTES)
    .addTag(activity.getString(R.string.job_tag))
    .build();
workManager.enqueue(ulpBackup);

这里是UlpBackup.class

public class UlpBackup extends Worker {
    private Integer responseCounter = 0;

    public UlpBackup() {}

    @NonNull
    @Override
    public Result doWork() {

        Log.d(logTag, "Starting periodic backup job";   
        final CountDownLatch countDownLatch = new CountDownLatch(1);

        /** Read from local database and upload to firestore **/

        localdb.setAPIListener(new APIListener() {
            @Override
            public void OnSuccess() {
                responseCounter++;
                if (responseCounter == 5) {
                    countDownLatch.countDown();
                }
            }

            @Override
            public void OnFailure() {
                responseCounter++;
                if (responseCounter == 5) {
                    countDownLatch.countDown();
                }
            }
        });

        localdb.sync();

        try {
            countDownLatch.await(300, TimeUnit.SECONDS);
        } catch (Exception exception) {
            Log.e(logTag, "Error in user list backup job " + exception.getMessage());
            return Result.FAILURE;
        }

        Log.e(logTag, "Ulp backup completed");
        return Result.SUCCESS;
}

上面的代码工作正常,工作发生大约每15分钟预期。 我不明白,唯一的一点是,每一次执行任务多次,有人可以解释为什么,我该如何避免呢?

从日志:

09-15 23:33:37.514 8190-8410: Starting periodic backup job
09-15 23:33:37.520 8190-8414: Starting periodic backup job
09-15 23:33:37.561 8190-8412: Starting periodic backup job
09-15 23:33:37.568 8190-8413: Starting periodic backup job
...
...
09-15 23:33:38.183 8190-8414: Ulp backup completed
09-15 23:33:39.164 8190-8412: Ulp backup completed
09-15 23:33:39.580 8190-8413: Ulp backup completed
09-15 23:38:37.517 8190-8410: Ulp backup completed

Answer 1:

您可以使用此方法如下: enqueueUniquePeriodicWork()并执行这样的:

WorkManager.getInstance().enqueueUniquePeriodicWork("YOUR_TAG", ExistingPeriodicWorkPolicy.KEEP, workRequest);

请注意,第二个参数是关键。 枚举可以KEEPREPLACE



Answer 2:

我认为我迟到回答这个问题,你可能有太多调整了..但我试图帮助反正..

我不明白,唯一的一点是,每一次执行任务多次, can someone explain我为什么,我怎么能避免呢?

说明:

每个人都会感到震惊,如果我会说:

  1. 谷歌的Android已经超过在实时基础上运行的过程亿卢比无法控制
  2. 它甚至还缺乏了解甚至说某某过程完成? 或运行? 或完成了吗?
  3. 就是这个。 而结果是你的问题

噢,我的上帝..这会导致data-loss ,如果我做任何数据库操作的话.. !! ??

是的,它会导致数据丢失很多次..

请问Android和开发商有任何变通那么......?

是的,尽量使用IntentService

什么是如此特殊的IntentService

如果intentservice已经运行即使thousands的时候,它被调用......然后,在那种情况下......所有来电都被保存在queue通过Android和处理one by oneone after another ,一个是后finished才另一个等待awakes ,并开始执行它

希望能帮助到你。



文章来源: Android Worker execute the job multiple times