我想在一天中的特定时间在后台执行一些任务 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/