N S*_*rma 19 android ios react-native react-native-android react-native-ios
我想在背景中的一天中的特定时间执行一些任务T.我发现在Android中有可能使用Headless JS.我发现这个库实现了这个https://github.com/vikeri/react-native-background-job并允许你在后台执行东西.
这不完全是我所期待的,它不允许您在特定时间安排任务T. 有谁知道这方面的任何工作?
我已检查此线程执行代码在特定时间反应原生我没有找到我的问题的解决方案.
jma*_*mac 15
我遇到了类似的问题,不幸的是,你不能在RN中指定类似于CRON动作的东西.
我对该问题的解决方案是使用此库https://github.com/ocetnik/react-native-background-timer并计算任务计划的当前时间和时间之间的差异.
计算出的时间应为ms,因此您可以使用提供的函数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);
}
请注意,此解决方案容易受到用户更改手机时间的影响.完美的解决方案是使用一些外部服务来获取时间.
第二个注意事项,应用程序至少需要在后台才能实现.
| 归档时间: | 
 | 
| 查看次数: | 4167 次 | 
| 最近记录: |