首页 > 解决方案 > 在本机反应中运行后台任务的最佳方法是什么?

问题描述

我正在构建一个应用程序,用户必须输入一个时间,一个简单的功能将在每天的特定时间触发。这可以在应用程序处于前台时处理。但是当应用程序处于关闭状态时。那没有使用,我找不到执行该功能的有效方法。

添加了最小的代码片段

async componentDidMount() {
  this.loadaccountDetail();
  this.interval = setInterval( () => this.setState(prevState => ({ timer: prevState.timer - 1 }) ),1000);
  SplashScreen.hide();
}


componentDidUpdate() {
  if (this.state.timer === 1) {
    clearInterval(this.interval);
  }
}


async loadaccountDetail() {
  let userId = await AsyncStorage.getItem("id");
  const user = JSON.parse(userId);
  this.setState({ user: user });
  try {
    var that = this;
    var date = moment().format("YYYY-MM-DD HH:mm:ss")
    var expirydate = this.props.matchapprovedate; //You can set your own date-time
    var diffr = moment.duration(moment(expirydate).diff(moment(date)));
    var hours = parseInt(diffr.asHours());
    var minutes = parseInt(diffr.minutes());
    var seconds = parseInt(diffr.seconds());
    var d = hours * 60 * 60 + minutes * 60 + seconds;
    //converting in seconds
    that.setState({ totalDuration: d });
    if(d == 10){
      this.abortDate()
    }
    else{
      console.log('not now')
    }
    this.setState({ data: !this.state.data });
  } 
  catch (err) {
    console.log("catch:" + err);
  }
}

abortDate() {
  ApiService.abortDate({ userid: this.props.userid })
  .then(async response => {
    if (response.status == 1) {
      NavigationService.navigate("news");
      ToastService.showToast("You canceled the date sucessfully","error",3000);
    }
    else {
      ToastService.showToast("Not able to cancel date", "error", 3000);
    }
  })
  .catch(err => {
    console.log(err)
  });
}

render() {
  const { matchapprovedate } = this.props;
  const { userid } = this.props;

  return (
    <View style={{flex:1}}>
      <CountDown
        digitStyle={{ backgroundColor: "transparent" }}
        digitTxtStyle={{ padding: 0, color: "#998299"}}
        timeLabelStyle={{ color: "#998299"}}
        until={this.state.totalDuration}
        //duration of countdown in seconds
        timeToShow={["H", "M", "S"]}
        timeLabels={{ h: "HH", m: "MM", s: "SS" }}
        onFinish={() => console.log('finished')}
        //on Finish call
        size={30}
      />

    </View>
  )
}


如前所述,当 var d 变为 10 时,我希望调用一个函数,该函数在安装此屏幕之前无法调用,即应用程序打开一次。

标签: react-native

解决方案


我推荐React Native Background Task,尽管它无法在特定时间可靠地执行您的任务(即:14:30 可能在 14:50 执行),它在 git hub 页面中解释为

任务执行的确切时间是不可预测的,因为 Anrdoid 和 iOS 都使用黑盒算法,这取决于设备睡眠状态等因素。这个库应该只用于增量功能的任务,并且可能有不精确的时间,例如数据的周期性后台同步。您应该为后台任务根本不触发的情况做好准备。


推荐阅读