How can I run background tasks in React Native?

And now there is react-native-background-task which is a single API for both Android and iOS.


I use this, and it seems to work: https://github.com/ocetnik/react-native-background-timer

Emit event periodically (even when app is in the background).

You can use the setInterval and setTimeout functions. This API is identical to that of react-native and can be used to quickly replace existing timers with background timers.

import BackgroundTimer from 'react-native-background-timer';

// Start a timer that runs continuous after X milliseconds
const intervalId = BackgroundTimer.setInterval(() => {
    // this will be executed every 200 ms
    // even when app is the background
    console.log('tic');
}, 200);

// Cancel the timer when you are done with it
BackgroundTimer.clearInterval(intervalId);

// Start a timer that runs once after X milliseconds
const timeoutId = BackgroundTimer.setTimeout(() => {
    // this will be executed once after 10 seconds
    // even when app is the background
    console.log('tac');
}, 10000);

// Cancel the timeout if necessary
BackgroundTimer.clearTimeout(timeoutId);

Currently, there is, unfortunately, no support for background tasks of any kind. The feature you are referring to would be a background timer. Such a timer is this product pain (a feature request) for react native, you may upvote it to show an increased demand for this feature.

EDIT 12/2016: There is still no real option. You have the Headless JS API since RN 0.33, but it is only for android. Also your App will crash if this runs in the foreground so you have to be careful about using it. Thanks to @Feng for pointing that out.