Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在react native中的特定时间安排后台作业_Android_Ios_React Native_React Native Android_React Native Ios - Fatal编程技术网

Android 如何在react native中的特定时间安排后台作业

Android 如何在react native中的特定时间安排后台作业,android,ios,react-native,react-native-android,react-native-ios,Android,Ios,React Native,React Native Android,React Native Ios,我想在react native中的后台在一天中的特定时间执行一些任务T。我认为这是可能的,在安卓系统中,现在使用。我发现这个库实现了这一点,并允许您在后台执行内容 这并不完全是我想要的,它不允许你在特定的时间安排任务。有人知道这方面的工作吗 我检查了这个线程,没有找到问题的解决方案。我遇到了一个类似的问题,不幸的是,您不能在RN中指定类似于CRON操作的内容 我解决这个问题的方法是使用这个库并计算当前时间和任务计划时间之间的差异 计算的时间应以毫秒为单位,因此您可以使用提供的函数setTimeo

我想在react native中的后台在一天中的特定时间执行一些任务T。我认为这是可能的,在安卓系统中,现在使用。我发现这个库实现了这一点,并允许您在后台执行内容

这并不完全是我想要的,它不允许你在特定的时间安排任务。有人知道这方面的工作吗


我检查了这个线程,没有找到问题的解决方案。

我遇到了一个类似的问题,不幸的是,您不能在RN中指定类似于CRON操作的内容

我解决这个问题的方法是使用这个库并计算当前时间和任务计划时间之间的差异

计算的时间应以毫秒为单位,因此您可以使用提供的函数
setTimeout

// Start a timer that runs once after X milliseconds
const timeoutId = BackgroundTimer.setTimeout(() => {
  // this will be executed once after 10 seconds
  // even when app is the the background
  console.log('tac');
}, 10000);
例如:

假设您希望将明天的任务安排在16号,在
componentDidMount
中,您可以计算从现在到计划日期之间的时间。让我们使用
力矩

componentDidMount(){
  const scheduledDate = 
   moment().add(1,'d').set({hour:16,minute:0,second:0,millisecond:0})
  const diffTime = scheduledDate.diff(moment())
  this.timeoutId = BackgroundTimer.setTimeout(() => {
    console.log('tac');
  }, diffTime);
}

componentWillUnmount(){
 BackgroundTimer.clearTimeout(this.timeoutId);
}
请注意,此解决方案易受用户更改手机时间的影响。完美的解决方案是使用一些外部服务来获取时间


第二个注意事项是,应用程序至少需要在后台才能运行。

创建类并将其添加到类中

public static final long NOTIFY_INTERVAL = 10 * 1000; // 30 minutes

@Override
    public void onCreate() {
        // cancel if already existed
        if (mTimer != null) {
            mTimer.cancel();
        } else {
            // recreate new
            mTimer = new Timer();
        }
        // schedule task
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
    }

class TimeDisplayTimerTask extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // code
                }
            });
        }
    }

JavaScript代码在前台只运行一个线程。如果您需要安排后台任务,则需要实现本机模块,如RN文档中所述:


当然,所有平台限制(尤其是iOS)都适用

将此代码放在您希望在后台运行的服务类中可能为时已晚,但这仍然是最好的方法吗?该库似乎在android中使用唤醒锁,而在应用程序处于后台时不会发布。这会耗尽电池电量。这仍然是最佳解决方案吗?这仅用于在appstate处于后台活动状态时运行任务。未处于关闭状态