React-native: Execute post request after 20 seconds, even if app goes on backgound

1.7k views Asked by At

When app runs in foreground, i execute successfully a POST-request using setTimeout with 20 seconds like this:

setTimeout(function() {
 /*POST request is done here*/ 
}, 20000);

Though, if in meanwhile user places the app on background, by pressing home button for example, then my post won't get fired after 20 seconds. On Android though, i checked that if 20 seconds get passed, and then i open the app(make it be in foreground), then post is executed immediately. (Haven't tested on ios to see if same thing happens). So i have the following questions:

1) Same behavior is happening on IOS side too?

2) Should i expect exactly same behavior if timeout had 15 mins timer and not 20 seconds?

3) How can i solve this problem? I need to contact to an endpoint after some time, and can't do it while app is in background with setTimeout.

Using libraries like react-native-background-task do not help in this situation, as i need to execute code after exactly 20 secs(or 10 mins etc) and not some time in future like 15 mins+

2

There are 2 answers

1
Ammar Tariq On

try this library it sets time what you want to set, but remember ios won't allow the time more than 30 sec

https://github.com/ocetnik/react-native-background-timer

3
meta4 On

I've had same kind of problem, and I used react-native-background-timer and it worked perfectly for Android.