Rapsssito / react-native-background-actions

React Native background service library for running background tasks forever in Android & iOS.
MIT License
819 stars 117 forks source link

On terminate and open new task/instance is created #141

Closed Rubioli closed 2 years ago

Rubioli commented 2 years ago

I have used the example code in the description for my app. Everything works fine and I see the background job running while in the foreground, background, and when the app is terminated.

After the termination when I open the app again, I see that a new stance is created and runs along side with the previous stance, so the app would create a new stance for each terminate and open. I tried to use the BackgroundService.isRunning() with condition and run stop() when its running in hope that it stops the previuse stance and creates a new one with no luck :/

How is it possible to only run one instance and not generate new ones when app is terminated and opened again?

My code:

import BackgroundService from 'react-native-background-actions';
import moment from 'moment';

const runTask = async () => {
  const sleep = (time) => new Promise((resolve) => setTimeout(() => resolve(), time));
  // You can do anything in your task such as network requests, timers and so on,
  // as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved),
  // React Native will go into "paused" mode (unless there are other tasks running,
  // or there is a foreground app).
  const veryIntensiveTask = async (taskDataArguments) => {
      // Example of an infinite loop task
      const { delay } = taskDataArguments;
      await new Promise( async (resolve) => {
          for (let i = 0; BackgroundService.isRunning(); i++) {
              console.log(i, moment().format('HH:mm:ss'));
              await sleep(delay);
          }
      });
  };

  const options = {
      taskName: 'Example',
      taskTitle: 'ExampleTask title',
      taskDesc: 'ExampleTask description',
      taskIcon: {
          name: 'ic_launcher',
          type: 'mipmap',
      },
      color: '#ff00ff',
      // linkingURI: 'yourSchemeHere://chat/jane', // See Deep Linking for more info
      parameters: {
          delay: 1 * 60 * 1000
      },
  };

  // iOS only Listen for the iOS-only expiration handler that allows you to 'clean up' shortly before the app’s remaining background time reaches 0
  // BackgroundService.on('expiration', () => {
  //   console.log('I am being closed :(');
  // });
  console.log('BackgroundService.isRunning()', BackgroundService.isRunning());
  if (BackgroundService.isRunning()) {
    console.log('Inside isRunning and stops');
    /await BackgroundService.stop();
  }
  await BackgroundService.start(veryIntensiveTask, options);
  // await BackgroundService.updateNotification({taskDesc: 'New ExampleTask description'}); // Only Android, iOS will ignore this call
  // iOS will also run everything here in the background until .stop() is called
}
Versions:
"react-native": "0.67.1",
"react-native-background-actions": "^2.6.7",

Thanks in advance!

zainarshad45122 commented 2 years ago

async componentDidMount() { console.log("BS", BackgroundService.isRunning()); const sleep = (time) => new Promise((resolve) => setTimeout(() => resolve(), time));

const veryIntensiveTask = async (taskDataArguments) => {
  // Example of an infinite loop task
  const { delay } = taskDataArguments;
  await new Promise(async (resolve) => {
    console.error('Before Loop');
    for (let i = 0; BackgroundService.isRunning(); i++) {
      console.log("Running in background");
      console.log('index', i);
      await sendRequest(db, 'signoff');
      console.log(delay);
      await sleep(delay);

    }
  });
};

const options = {
  taskName: 'BackGroundTask',
  taskTitle: 'Background Task',
  taskDesc: 'App running in background',
  taskIcon: {
    name: 'ic_launcher',
    type: 'mipmap',
  },
  color: '#ff00ff',
  linkingURI: 'yourSchemeHere://chat/jane', // See Deep Linking for more info
  parameters: {
    delay: 10000,
  },
};

**if(!BackgroundService.isRunning()) // Add this line to your code, this will check if any instance is already running so it won't start a new one**
{
  await BackgroundService.start(veryIntensiveTask, options);
  await BackgroundService.updateNotification({ taskDesc: 'App running in background' }); // Only Android, iOS will ignore this call
  // iOS will also run everything here in the background until .stop() is called
  await BackgroundService.stop

}

}

Rubioli commented 2 years ago

Thank you so much @zainarshad45122