Reputation: 2299
I am working on a react native app for users to track their gym workouts. I wanted to start a timer when the user starts their workout. During their workout they will type in information and then most likely lock the phone and maybe even use other apps during their workout. Running a simple setInterval to keep track of the time does not work because once the app is in the background no JS is able to run anymore. I found this library that uses native code https://github.com/ocetnik/react-native-background-timer to keep your javascript running in the background but it seems to have some bugs at the moment. I found that after 10 seconds in the background the JS logic stops running.
react-native: "0.60.5
Upvotes: 6
Views: 9373
Reputation: 2299
The answer I ended up with was to stop trying to run a timer in the background and instead use timestamps to compute the difference between 2 times since its difficult to reliably run logic in the background in a cross platform way without a lot of added complexity.
Using the function below I would generate a timestamp with moment.js when the timer needs to start and then when the timer needs to stop generate another timestamp and calculate the difference between them.
const getCurrentTimeInWithMomentLibary = moment().format( 'MM/DD/YYYY HH:mm:ss' );
const diffTime = ( then, now ) => {
const ms = moment( now, 'MM/DD/YYYY HH:mm:ss' )
.diff( moment( then, 'MM/DD/YYYY HH:mm:ss' ) );
const duration = moment.duration( ms );
const hours = Math.floor( duration.asHours() );
const currentDate = moment().format( 'MM/DD/YYYY' );
const time = `${ hours }:${ moment.utc( ms ).format( 'mm:ss' ) }`;
return `${ currentDate } ${ time }`;
};
Upvotes: 8
Reputation: 13926
For Android
, it can be resolved through a module in React-native
. But it only works on Android
.
import {HeadlessJsTaskError} from 'HeadlessJsTask';
module.exports = async (taskData) => {
const condition = ...;
if (!condition) {
throw new HeadlessJsTaskError();
}
};
Upvotes: 0
Reputation: 48006
Not a direct answer to your question but a suggestion that might make this issue irrelevant...
Assuming your users actually enter a start and end time for their workout, you will be able to calculate the amount of time spent working out using these timestamps.
Subtracting the start time from the end time would give you a duration of the users workout.
Upvotes: 2