title: What is the best way to run background task in react native?
body: <p>I am building an app where in user have to enter a time and a simple function will trigger on each day at that particular time. This can be handled when the app is in foreground. But when the app is in closed state. That is not using, I cannot find an efficient way to execute that function.</p>
  
  <p>Added the minimal code snippet</p>
  
  <pre><code>async componentDidMount() {
    this.loadaccountDetail();
    this.interval = setInterval( () =&gt; this.setState(prevState =&gt; ({ 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 =&gt; {
      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 =&gt; {
      console.log(err)
    });
  }
  
  render() {
    const { matchapprovedate } = this.props;
    const { userid } = this.props;
  
    return (
      &lt;View style={{flex:1}}&gt;
        &lt;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={() =&gt; console.log('finished')}
          //on Finish call
          size={30}
        /&gt;
  
      &lt;/View&gt;
    )
  }
  
  
  </code></pre>
  
  <p>As mentioned when the var d becomes 10 i want a function to be called which cannot be called until this screen is mounted that is the app is opened once.</p>