1

有没有办法以 react native expo 为例来做后台任务?我只想每 5 秒创建一次 post 方法,并 console.log 看看它是否在这个例子中工作:

这是示例的站点

我想改变这个例子,我想尝试使用它来满足我的需要,那么我如何每 5 秒创建一次 post 方法并在后台创建 console.log 呢?

import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';

const FETCH_TASKNAME = 'test_task'
const INTERVAL = 60

function test() {
    console.log('function is running')
}

export async function registerFetchTask() {
    TaskManager.defineTask(FETCH_TASKNAME, test);

    const status = await BackgroundFetch.getStatusAsync();
    switch (status) {
        case BackgroundFetch.Status.Restricted:
        case BackgroundFetch.Status.Denied:
            console.log("Background execution is disabled");
            return;

        default: {
            console.debug("Background execution allowed");

            let tasks = await TaskManager.getRegisteredTasksAsync();
            if (tasks.find(f => f.taskName === FETCH_TASKNAME) == null) {
                console.log("Registering task");
                await BackgroundFetch.registerTaskAsync(FETCH_TASKNAME);

                tasks = await TaskManager.getRegisteredTasksAsync();
                console.debug("Registered tasks", tasks);
            } else {
                console.log(`Task ${FETCH_TASKNAME} already registered, skipping`);
            }

            console.log("Setting interval to", INTERVAL);
            await BackgroundFetch.setMinimumIntervalAsync(INTERVAL);
        }
    }

}

4

1 回答 1

0

试试这个expo-background-fetch库。这正是您在世博会上所需要的。

import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';

TaskManager.defineTask(YOUR_TASK_NAME, () => {
  try {
    const receivedNewData = // do your background fetch here
    return receivedNewData ? BackgroundFetch.Result.NewData : BackgroundFetch.Result.NoData;
  } catch (error) {
    return BackgroundFetch.Result.Failed;
  }
});

希望能帮助到你

于 2020-01-30T08:55:21.123 回答