Rapsssito / react-native-background-actions

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

BackgroundService.start create multiple task #170

Closed Allan-Tecchio closed 4 months ago

Allan-Tecchio commented 1 year ago

When I kill my application and open it again and run BackgroundService.start it creates 2 tasks, even running BackgroundService.stop

BillDelvin commented 1 year ago

Hi.. I'm face the same issue, is there any way to solve this problem ?

alexfov commented 1 year ago

Duplicate https://github.com/Rapsssito/react-native-background-actions/issues/121 here is the original issue. It's not solved yet.

alexfov commented 1 year ago

I made a crunch to solve the problem without touching the native part.

//this variable is persistent until the app is reloaded with service off
//so we check in a task if the fn argument is the same as 'iteration'
//if it is not we should stop backgroundTask
export let iteration = 0;

export const startBackgroundService = (isThereActiveShift: boolean) => {
  if (!BackgroundService.isRunning()) {
    iteration++;
    BackgroundService.start(backgroundTask.bind(null, iteration), taskOptions)
  } 
};

export const backgroundTask = async (index: number, taskDataArguments: { delay: number }) => {
  await new Promise<void>(async (resolve) => {
    for (let i = 0; BackgroundService.isRunning(); i++) {
      console.log({ index, iteration });
      if (index !== iteration) return;
      //your logic here
    }
  });
};

Ofcourse it's not an ideal solution but it works.

Lunatic-coder001 commented 1 year ago

But know I think the problem of multiple task running simuntenously is solved and my code was this useEffect(() => { Linking.getInitialURL().then(url => { console.log("uuu", url) if (url !== null) { // if opened from notification if app is killed

  }
}).catch(err => console.error('An error occurred', err));
let subcribtion = Linking.addEventListener('url', handleOpenURL);
subcribtion.subscriber;

return () => {
  subcribtion.remove();
};

}, []); // Linking.addEventListener('url', handleOpenURL);

function handleOpenURL(evt) { // Will be called when the notification is pressed foreground console.log(evt.url); // do something } is my code not working properly

mlwong54 commented 1 year ago

Hi. Encounter the problem. I tried adding a delay function after the stop call. Sometimes it works but sometimes the task is not properly killed. There are still multiple task happening.