android - react-native 如何在特定时间安排后台作业

标签 android ios react-native react-native-ios

我想在一天中的特定时间在后台执行一些任务 T,以响应 native 。我看到现在可以在 android 中使用 Headless JS .我发现这个库实现了这个 https://github.com/vikeri/react-native-background-job并允许你在后台执行东西。

这并不完全是我想要的,它不允许您在特定时间安排任务 T。有谁知道解决这个问题?

我已经检查了这个帖子 Execute code at specific time in react native我没有找到解决问题的方法。

最佳答案

我遇到了类似的问题,很遗憾,您无法在 RN 中指定类似于 CRON 操作的内容。

我对这个问题的解决方案是使用这个库 https://github.com/ocetnik/react-native-background-timer并计算当前时间与任务计划时间之间的差异。

计算的时间应该以毫秒为单位,因此您可以使用提供的函数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 中你可以计算从现在到预定日期的时间。让我们使用 moment:

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);
}

请注意,此解决方案容易受到用户更改手机时间的影响。完美的解决方案是使用一些外部服务来获取时间。

第二点,应用程序至少需要在后台才能运行。

关于android - react-native 如何在特定时间安排后台作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45825585/

相关文章:

java - 将 JSoup 传递给 String []

java - 从类继承并在新类中更改其父类

android - 进程 'command ' F :\android-sdk\build-tools\21. 1.2\aapt.exe'' 以非零退出值 1 完成

ios - 如何正确组合 CGAffineTransform 矩阵?

android - 将项目添加到 Android React Native Developer 菜单

android - 如何在 Kotlin 中将对象列表从 Activity A 传递到 Activity B?

objective-c - 点符号与方法符号

ios - 检查用于在 Swift 中编译应用程序的 Xcode/iOS SDK 版本

react-native - 引用错误 : `import` a file after the Jest environment has been torn down

react-native - React Native Navigation Drawer - 打开不在抽屉中的页面