简体   繁体   English

react-native 无头 js 任务中的超时

[英]Timeout in a react-native headless js task

I am developing a react-native applicaton with a headless js task to make some background work.我正在开发一个带有无头 js 任务的 react-native 应用程序来完成一些后台工作。

I need to execute some code after an amount of time, but noticed that using setTimeout execution gets suspended until the app is again in foreground.我需要在一段时间后执行一些代码,但注意到使用 setTimeout 执行被暂停,直到应用程序再次处于前台。

Anyone has idea why this happens and know how to solve or workaround this?任何人都知道为什么会发生这种情况并知道如何解决或解决这个问题?

EDIT编辑

A simple example一个简单的例子

module.exports = async (taskData) => {

    for (let i = 0; i < 30; i++) {
        setTimeout(function(){
            console.log(i);            
        }, 1000*i + 100);
    }

    return;
}

I faced the same issue and went into debugging it.我遇到了同样的问题并开始调试它。 The problem is with how the ReactContext is constructed when your app is in the background.问题在于当您的应用程序在后台时如何构造 ReactContext。 The context signals to have been created BEFORE the TimingModule<\/code> is initialized and your task is instantly executed by the HeadlessJsTaskService<\/code> (before the TimingModule<\/code> is initialized).TimingModule<\/code>初始化之前创建的上下文信号,并且您的任务由HeadlessJsTaskService<\/code>立即执行(在TimingModule<\/code>初始化之前)。

However the TimingModule<\/code> adds a listener to the HeadlessJsTaskContext<\/code> in order to only run while there are active background tasks.但是TimingModule<\/code>向HeadlessJsTaskContext<\/code>添加了一个侦听器,以便仅在有活动的后台任务时运行。 This listener is attached in TimingModule.initialize()<\/code> - but due to the execution order this listener is attached after your task was already started, meaning it is never invoked and thereby the TimingModule<\/code> is not running.此侦听器附加在TimingModule.initialize()<\/code>中 - 但由于执行顺序,此侦听器是在您的任务已经启动之后附加的,这意味着它永远不会被调用,因此TimingModule<\/code>没有运行。

This can be fixed by declaring HeadlessJsTaskContext.addTaskEventListener(...)<\/code> as synchronized<\/code> and then invoking the added listeners for every currently active task.这可以通过将HeadlessJsTaskContext.addTaskEventListener(...)<\/code>声明为已synchronized<\/code> ,然后为每个当前活动的任务调用添加的侦听器来解决。 Before:前:

  public void addTaskEventListener(HeadlessJsTaskEventListener listener) {
    mHeadlessJsTaskEventListeners.add(listener);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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