React Native Background Timer
Emit event periodically (even when app is in the background).
Installation
npm i react-native-background-timer --save
react-native link
Installation using CocoaPods on iOS
npm i react-native-background-timer --save
- add the following to your Podfile:
pod 'react-native-background-timer', :path => '../node_modules/react-native-background-timer'
Usage Crossplatform
To use the same code both on Android and iOS use runBackgroundTimer() and stopBackgroundTimer(). There can be used only one background timer to keep code consistent.
BackgroundTimer.runBackgroundTimer(() => {
},
3000);
BackgroundTimer.stopBackgroundTimer();
Android didn't tested as well.
Usage iOS
After iOS update logic of background task little bit changed. So we can't use as it was.
You have to use only start() and stop() without parameters. And all code that is performing will continue performing on background including all setTimeout() timers.
Example:
BackgroundTimer.start();
BackgroundTimer.stop();
If you call stop() on background no new tasks will be started!
Don't call .start() twice, as it stop performing previous background task and starts new.
If it will be called on backgound no tasks will run.
Usage Android
You can use the setInterval
and setTimeout
functions.
This API is identical to that of react-native
and can be used to quickly replace existing timers
with background timers.
import BackgroundTimer from 'react-native-background-timer';
const intervalId = BackgroundTimer.setInterval(() => {
console.log('tic');
}, 200);
BackgroundTimer.clearInterval(intervalId);
const timeoutId = BackgroundTimer.setTimeout(() => {
console.log('tac');
}, 10000);
BackgroundTimer.clearTimeout(timeoutId);
Obsolete
Obsolete usage which doesn't allows to use multiple background timers.
import {
DeviceEventEmitter,
NativeAppEventEmitter,
Platform,
} from 'react-native';
import BackgroundTimer from 'react-native-background-timer';
const EventEmitter = Platform.select({
ios: () => NativeAppEventEmitter,
android: () => DeviceEventEmitter,
})();
BackgroundTimer.start(5000);
EventEmitter.addListener('backgroundTimer', () => {
console.log('toe');
});
BackgroundTimer.stop();