What is the best way to schedule a task in react native?

jsdario picture jsdario · Oct 9, 2016 · Viewed 22.1k times · Source

There are different ways to run tasks in the background in Android and iOS respectively. I have found What is the best way to schedule task in android? as well on stack overflow.

I am wondering which is the best way using react-native only. Would it be good enough to use setInterval or setTimeout for tasks that have to run daily or every few hours?

Would not those tasks be killed by the OS?

Any ideas or suggestions?

Answer

jsdario picture jsdario · Jan 20, 2017

I will answer my own question to see if this information can be of used by anyone looking for it.

Since the different mobile OSs tend to kill background jobs, or stall them to save battery, there are few deterministic methods to schedule tasks in react native. I use a combination of the following:

Beware of the dragons: your app might be closed if it abuses execution time or memory usage after a system wake up. You may have to rehydrate all listeners after the phone was left without battery. So the user still needs to interact heavily with your app.

Update: From Android O there are very strict background execution limits. When using a HeadlessJSTask service, ensure that it is launched as a foreground service if you want it to last longer than a few seconds. It may require a notification with it. Take into account that only loading the bundle can take up to a few seconds, depending on your app and the device.