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

Why do both tasks continue to run despite a stop() ? #109

Closed GaylordP closed 3 years ago

GaylordP commented 3 years ago

Hello and sorry for my bad english, I'm french :)

Thanks you very much for your library. :)

I created a Timer module, which triggers a countdown. I want this Timer to stop when leaving the screen. I put my code in a useEffect :

useEffect(() => {
    startBackgroundService()

    return () => stopBackgroundService()
}, [])

Sometimes when the user goes to the next screen I trigger a new Timer with others parameters (including the departure time, to display a countdown in notifications) . In this situation, the first countdown does not have time to stop and both tasks continue to run

I created a simplified example to show my problem.

In this situation, I don't understand why two timers are running in the background:

const sleep = (time) => new Promise((resolve) => setTimeout(() => resolve(), time))

const backgroundTask = async (taskData) => {
  await new Promise(async (resolve) => {
      const { delay } = taskData;

      for (let i = 0; BackgroundService.isRunning(); i++) {
        console.log('// ' + i)

        await BackgroundService.updateNotification({
          taskDesc: 'rest : ' + i,
        });
        await sleep(delay);
      }
  });
}

const startBackgroundService = async () => {
  await BackgroundService.start(backgroundTask, {
    taskName: 'training',
    taskTitle: 'name',
    taskDesc: 'description',
    taskIcon: {
      name: 'ic_small_icon',
      type: 'drawable',
    },
    parameters: {
      delay: 1000,
    }
  })
}

const stopBackgroundService = async () => {
  await BackgroundService.stop()
}

const Timer = () => {
  useEffect(() => {
    startBackgroundService()
    stopBackgroundService()
    startBackgroundService()
  }, [])

  ...
}

LOG // 0 LOG // 0 LOG // 1 LOG // 1 LOG // 2 LOG // 2 LOG // 3 LOG // 3 LOG // 4 LOG // 4 LOG // 5 LOG // 5 ...

GaylordP commented 3 years ago

I found an alternative solution, thank you :)

alexfov commented 3 years ago

I found an alternative solution, thank you :)

Could you share it please?