ocetnik / react-native-background-timer Goto Github PK
View Code? Open in Web Editor NEWEmit event periodically (even when app is in the background)
License: MIT License
Emit event periodically (even when app is in the background)
License: MIT License
Which android version can be supported?
How about IOS?
when the app runs in background , the timer is slower than in foreground.
intervalId = BackgroundTimer.setInterval(() => {
var curSecond = this.state.curSecond +1;
this.setState({curSecond:curSecond });
}, 1000);
Thank you
I am starting the timer on state change:
_handleAppStateChange(currentAppState) {
var me = this;
var str = me.currentAppState.currentState
if (currentAppState == 'background') {
intervalId = BackgroundTimer.setInterval(() => {
me.sendCallToAPI(str);
console.log('tic');
}, 60000);
}
}
but what I notice it stops after couple of minutes, while in background, I am storing data in a DB on API call and after couple of entries it stop it.
Hi guys,
I'm having this intermittent error (50%) on ios simulator reload:
<Error>: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'bridge is not set. This is probably because you've explicitly synthesized the bridge in RNBackgroundTimer, even though it's inherited from RCTEventEmitter.'
Any ideas why this is happening? This is strange given the last release, where I don't see the synthesize of the bridge anymore.
undefined is not an object (evaluating 'RNBackgroundTimer.setTimeout') what meaning this error?
When being in a low memory environment, if I launch for example Music or if I get a phone call, the application simply get's killed and the backgroundTimer no longer works. This is because the app process is killed.
One way to solve this is to use a Service. It's running independently from the RN Lifecycle, but when the app process is requested to be killed the Services can still access the Javascript Code. In application for sure the components are unmounted, but the RCT Pub/Sub system still works. I made a few tests with a native chronometer and it works fine. Just make sure to call the unsubscribe method whenever the Root component is unmouted (when the app is asked to be closed by the user).
What do you think ?
Maybe this is the place for a special "long-run" mode in case of playing music or whatever. I'm using it with a Chronometer to update the time periodically.
I'm testing this module by setting up a timer to log the time every 10 minutes and running it for extended periods. When I check the times logged, it is sometimes every 10 minutes, but sometimes switches to a new, longer interval. It is weirdly consistent when it switches, the new interval lasting potentially for hours and being stable to within 10 or so seconds. I've seen intervals around 14, 16, or even 21 minutes, so it isn't just a clean multiple of the original.
Has anyone else experienced this instability or know why it is?
I would like to have a button in my app where depending on whether the background job is running already i.e. there is a property set in callbacks
then the button would show 'Stop Background Job' otherwise, 'Start Background Job'.
It would be great to have an interface that returns callbacks
React Native's latest source mentions in the RCTDeviceEventEmitter
class:
Deprecated - subclass NativeEventEmitter to create granular event modules instead of adding all event listeners directly to RCTDeviceEventEmitter.
Steps that cause the error:
create-react-native-app
yarn add react-native-background-timer
react-native link
yarn start
Code that leads to the issue:
startFetching() {
console.log("start fetching")
const timerId = BackgroundTimer.setInterval(() => {
console.log("Fetching");
}, parseInt(this.state.intervalInput, 10));
this.setState({
fetchInterval: timerId
});
}
As far as I can tell const RNBackgroundTimer = NativeModules.RNBackgroundTimer;
does not work in our case. Could it be that this library is simply incompatible with create-react-native-app
projects that have not yet ejected?
App often crash when reload in debug mode with the message below:
"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'bridge is not set. This is probably because you've explicitly synthesized the bridge in RNBackgroundTimer, even though it's inherited from RCTEventEmitter.'"
iOS: 10.3
React-native: 0.47.2
react-native-background-timer: 1.2.0
Followed installations and the example specified in "Usage". However in the React Native Debugger in Chrome, only the first message "tic" get logged when the App is active. When the app goes to background, no messages "tic" got logged. Not sure what I missed.
Xcode: 8.2.1
NPM: 3.10.10
"react": "16.0.0-alpha.12",
"react-native": "0.45.1",
While using react native with expo and the background timer, my phone displayed "Native module cannot be null". What does this mean and how can I fix it?
Hi Dávid,
First of all, thanks for writing this library, awesome work! 👍
Hey, currently it is not possible to use multiple background timers. This makes it complicated to use the library when it is used from multiple places in your app. What would you think of adding an API similar to that of setInterval
and setTimeout
? This would solve the problem and you could also easily replace existing setTimeout/setInterval code with react-native-background-timer
. Like this:
const interval = BackgroundTimer.setInterval(() => {
console.log('this will run even if the app is in the background, woohoo :)');
}, 200);
BackgroundTimer.clearInterval(timer);
const timeout = BackgroundTimer.setTimeout(() => {
console.log('this will run even if the app is in the background, woohoo :)');
}, 200);
BackgroundTimer.clearTimeout(timeout);
What do you think about this? I could add this with relative easy if you think it's good idea.
Cheers, Hein
I'm getting this error:
This is the source code:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
} from 'react-native';
import BackgroundTimer from 'react-native-background-timer';
class WorkerSampleApp extends Component {
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => {
// 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);
// Cancel the timeout if necessary
BackgroundTimer.clearTimeout(timeoutId);
}}>
<Text style={styles.welcome}>
Send message
</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('WorkerSampleApp', () => WorkerSampleApp);
Please help...
Hey @ocetnik I'm trying to get a better understanding of how this package works.
The README mentions that it can fire a timer when the app is in the background.
Looking through the codebase it looks like to me you are scheduling stuff with
import android.os.Handler;
My understanding is that Handlers will only fire when the app is in the background and the phone is on. If the phone screen has been turned off and no app has a WakeLock then I believe the handler will no longer fire.
If this is needed then an AlarmManager is needed... does that sound right to you?
I've just upgraded to the following and the timer no longer works in background. It was working fine before the upgrade.
react-native-cli: 2.0.1
react-native: 0.48.1
When I try to install via npm I get the following answer:
UNMET PEER DEPENDENCY [email protected]
Am I maybe doing something wrong or is it simply not compatible with RN 0.45?
thanks!
I installed and linked:
npm install --save react-native-background-timer
react-native link
And I put this in componentDidMount
of my top level component.
this.intervalId = BackgroundTimer.setInterval(this.beatHeart.bind(this), minutesPerHearbeat * 60 * 1000)
When I run the app the emulator, I immediately get this. I guess I'm missing something obvious?
undefined is not an object (evaluating 'RNBackgroundTimer.setTimeout')
setInterval
index.js:48
componentDidMount
app.js:63
invokeComponentDidMountWithTimer
ReactCompositeComponent.js:54
notifyAll
CallbackQueue.js:67
close
ReactNativeReconcileTransaction.js:38
closeAll
Transaction.js:204
perform
Transaction.js:151
perform
Transaction.js:138
perform
ReactUpdates.js:90
flushBatchedUpdates
ReactUpdates.js:173
closeAll
Transaction.js:204
perform
Transaction.js:151
batchedUpdates
ReactDefaultBatchingStrategy.js:63
enqueueUpdate
ReactUpdates.js:201
enqueueUpdate
ReactUpdateQueue.js:25
enqueueSetState
ReactUpdateQueue.js:209
setState
ReactComponent.js:64
<unknown>
setup.js:28
<unknown>
store.js:26
complete
persistStore.js:54
<unknown>
persistStore.js:47
complete
getStoredState.js:82
<unknown>
getStoredState.js:61
<unknown>
AsyncStorage.js:87
__invokeCallback
MessageQueue.js:231
<unknown>
MessageQueue.js:103
guard
MessageQueue.js:41
invokeCallbackAndReturnFlushedQueue
MessageQueue.js:102
I installed react-native-background-timer with Ract-Native.
"react": "15.4.1",
"react-native": "0.39.1",
"react-native-background-timer": "^0.1.3",
How can I fix it? Please help me check.
Thanks so much. @ocetnik
Hi,
I do implement BackgroundTimer
in componentDidMount
, but getting error in node-modules/react-native-background-time/index.js
line 48
RN: 0.40.0
Please help take a look.
Hi, I'm using the timer on Android and it's working great. However, I am unable to shut it down cleanly when exiting the app. I tried the following code but the function never gets called. Any ideas?
Thanks.
componentWillUnmount() {
console.log('unmount');
BackgroundTimer.clearInterval(intervalId);
}
Got this error after installation/link:
ld: library not found for -lRCTActionSheet
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I had two calls in my app to BackgroundTimer.setInterval. One at 200 ms and the other at 10s. The one listed at 10s would run 10 times every time it ran. Any idea what is happening here?
I'm hitting an error on react-native-background-timer/index.js:58:17 in Android and iOS:
undefined is not an object (evaluating 'this.callbacks[a]={callback:e,interval:!0,timeout:t}')
I'm still looking for a consistent set of steps to reproduce as the timers are working properly for some of my users and not for others.
I'm on 1.0.3 currently and will update if I can track down more specifics.
Thanks!
When running the same app on Android and iOS, it works perfectly on Android, but on iOS the timer pauses when either pressing the home button or the sleep button. What might I be doing wrong?
I've upgraded to the latest RN version and am noticing that when going from background to foreground, the time between is lost whereas before, it would keep counting in the background. This seems like a major regression. On the simulator I am not experiencing this issue.
Lexical or Preprocessor issue...
Had to remove the React/ prefixes on all your .h's and m's.
Need to update that link. :)
ENV
RN 0.45
iPhone 6 Emulator
Problem
The console of Xcode continue print "Can't endBackgroundTask: no background task exists with identifier ??, or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.".
when the app is in foreGround, it is ok.
would you give me some advices? thanks
I am trying to reduce the number of operations handled by the View thread following https://facebook.github.io/react-native/docs/performance.html so I wonder if anyone has actually benchmarked if it's better to have intervals and backgrounds using react-native-background-timers
.
Hi, there are too much log(eg: nw_socket_set_common_sockopts setsockopt SO_NOAPNFALLBK failed: [42] Protocol not available, dumping backtrace...).It 's not convenient to debug, how can I stop log? Thanks.
When trying to run my android project, I receive the following error and the build is failing:
/node_modules/react-native-background-timer/android/src/main/java/com/ocetnik/timer/BackgroundTimerPackage.java:26: error: method does not override or implement a method from a supertype @Override
What can be one of the causes?
when I try to add your component start getting following error:
Mask type not supported.
because of this:
<TextInputMask
style={styles.input}
ref={'phoneText'}
type={'us-phone'}
placeholder='Phone Number'
value={this.state.Phone}
onChange={(event) => this.setState( {Phone: event.nativeEvent.text})}
/>
Good afternoon. I have a sound application who works with a timer. When i to slide to background and open another application for example iMusic my timer stopped. Any body know how to fix that???
Hi, it's a wonderful library and really easy to install. Do you have any road map to include Background service even after the app is killed from the app switcher? Thanks in advance.
I've installed and imported the react-native-background-timer module.
I've added the code exactly as shown in your readme for setInterval or setTimeout, but I am getting "Can not read property setTimeout of undefined" error.
I am able to log the BakckgroundTimer Object value which is looking fine(Means it is not actually undefined). But whenever I try to call setTimeout or setInterval method it gives me error.
Do we need to do any other configuration apart from what is shown in readme.md?
If no, Can you help me figure out this issue?
I'm using BackgroundTimer.setInterval for countdown 20' minute , but when time remain about 3 minute then App crash .Noticed I'm using setInterval for a time smaller 15 minute then not appear crashed and if I using setInterval exist of react-native then not crash. I'm using react-native 0.36 and react-native-background-timer: "0.1.3" . Anybody Could help me ?
android 4.1 device
"react-native": "0.48.1",
"react-native-background-timer": "1.2.0",
const EventEmitter = Platform.select({
ios: () => NativeAppEventEmitter,
android: () => DeviceEventEmitter,
})();
BackgroundTimer.start(5000);
EventEmitter.addListener('backgroundTimer', () => {
// this will be executed every 5 seconds
// even when app is the the background
console.log('toe',ws.readyState); //stoped when wifi tun off
});
running application ,the background timer task run success,
then return the app ,the app run back,timer task run ok in this time,
but the timer task stopped when i change the wifi status ,
so my problem is the timer task stopped when the app run back and change the network status。
It would be very useful! ;-)
as title says
I ran the two steps that you have on the NPM page
npm i react-native-background-timer --save
react-native link
But when I go to start it, I get this error on Windows 10:
$ react-native run-android
Scanning 582 folders for symlinks in E:\Sites\Skytango\app\node_modules (28ms)
JS server already running.
Building and installing the app on the device (cd android && gradlew.bat installDebug)...
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42301Library UP-TO-DATE
:app:prepareComFacebookFbuiTextlayoutbuilderTextlayoutbuilder100Library UP-TO-DATE
:app:prepareComFacebookFrescoDrawee101Library UP-TO-DATE
:app:prepareComFacebookFrescoFbcore101Library UP-TO-DATE
:app:prepareComFacebookFrescoFresco101Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipeline101Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineBase101Library UP-TO-DATE
:app:prepareComFacebookFrescoImagepipelineOkhttp3101Library UP-TO-DATE
:app:prepareComFacebookReactReactNative0472Library UP-TO-DATE
:app:prepareComFacebookSoloaderSoloader010Library UP-TO-DATE
:app:prepareOrgWebkitAndroidJscR174650Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:mergeDebugShaders UP-TO-DATE
:app:compileDebugShaders UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:incrementalDebugJavaCompilationSafeguard UP-TO-DATE
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
E:\app\android\app\src\main\java\com\app\MainApplication.java:6: error: package com.ocetnik.timer does not exist
import com.ocetnik.timer.BackgroundTimerPackage;
^
E:\app\android\app\src\main\java\com\app\MainApplication.java:7: error: package com.ocetnik.timer does not exist
import com.ocetnik.timer.BackgroundTimerPackage;
^
E:\app\android\app\src\main\java\com\app\MainApplication.java:28: error: cannot find symbol
new BackgroundTimerPackage(),
^
symbol: class BackgroundTimerPackage
E:\app\android\app\src\main\java\com\app\MainApplication.java:29: error: cannot find symbol
new BackgroundTimerPackage()
^
symbol: class BackgroundTimerPackage
4 errors
:app:compileDebugJavaWithJavac FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 9.548 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html
Any help would be appreciated as I could use this functionality. Thanks!
Is this library not working on ios simulator ?
when I test this plugin in version lower than 4.3 or equal, my application crash, would anyone have any solution?
I'm green to iOS for sure... This was my first time adding a pod so I went to my ios folder did pod init and it created this file:
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'aura_react_native' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for aura_react_native
target 'aura_react_native-tvOSTests' do
inherit! :search_paths
# Pods for testing
end
target 'aura_react_nativeTests' do
inherit! :search_paths
# Pods for testing
end
end
target 'aura_react_native-tvOS' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for aura_react_native-tvOS
target 'aura_react_native-tvOSTests' do
inherit! :search_paths
# Pods for testing
end
end
then from my ios project folder in ran you command on the readme and get the message 'is a directory' see screen shot.
I have
BackgroundTimer.start(5000);
DeviceEventEmitter.addListener('backgroundTimer', () => {
this._startDailyTimer();
});
inside ComponentDidMount(), but I get an error saying:
Possible Unhandled Promise Rejection (id: 0): undefined is not an object.
Do these BackgroundTimer functions have to be used in the global scope, or am I doing something else wrong here?
Thank you.
Hi, how do I call one of my functions from the timer. For example, in index.android.js
import BackgroundTimer from 'react-native-background-timer';
const intervalId = BackgroundTimer.setInterval(() => {
console.log('tic 1'); // This displays ok.
this.tick(); // This gives undefined is not an object (evaluating '_this.tick')
}, 3000);
class Test extends Component {
tick() {
console.log('tic 2');
}
}
Thanks
It seems it's also the case on IOS (see #9 ) and now I just tested it on Android and it's not working when the phone is locked.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.