{"id":13472767,"url":"https://github.com/jamesisaac/react-native-background-task","last_synced_at":"2025-05-15T19:06:10.401Z","repository":{"id":17611126,"uuid":"82345864","full_name":"jamesisaac/react-native-background-task","owner":"jamesisaac","description":"Periodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed.","archived":false,"fork":false,"pushed_at":"2023-04-28T16:55:28.000Z","size":38,"stargazers_count":1110,"open_issues_count":67,"forks_count":111,"subscribers_count":11,"default_branch":"master","last_synced_at":"2025-05-14T11:51:41.122Z","etag":null,"topics":["android","background-jobs","fetch","ios","offline","react-native","sync"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jamesisaac.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-02-17T23:07:27.000Z","updated_at":"2025-05-10T00:15:41.000Z","dependencies_parsed_at":"2024-01-16T06:10:11.865Z","dependency_job_id":"da7ac382-22c0-4f0c-b016-077d18b0b2bf","html_url":"https://github.com/jamesisaac/react-native-background-task","commit_stats":{"total_commits":26,"total_committers":1,"mean_commits":26.0,"dds":0.0,"last_synced_commit":"3db6df10d80dbbd8e8fd3ee1c964bd332decc5e0"},"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamesisaac%2Freact-native-background-task","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamesisaac%2Freact-native-background-task/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamesisaac%2Freact-native-background-task/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamesisaac%2Freact-native-background-task/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jamesisaac","download_url":"https://codeload.github.com/jamesisaac/react-native-background-task/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254161533,"owners_count":22024789,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["android","background-jobs","fetch","ios","offline","react-native","sync"],"created_at":"2024-07-31T16:00:57.807Z","updated_at":"2025-05-15T19:06:10.371Z","avatar_url":"https://github.com/jamesisaac.png","language":"Java","readme":"# react-native-background-task\n\n[![npm version](https://img.shields.io/npm/v/react-native-background-task.svg)](https://www.npmjs.com/package/react-native-background-task)\n[![license](https://img.shields.io/github/license/jamesisaac/react-native-background-task.svg)](https://opensource.org/licenses/MIT)\n[![npm downloads](https://img.shields.io/npm/dm/react-native-background-task.svg)](https://www.npmjs.com/package/react-native-background-task)\n\nPeriodic background tasks for React Native apps, cross-platform (iOS and\nAndroid), which run even when the app is closed.\n\nThis library allows the scheduling of a single periodic task, which executes\nwhen the app is in the background or closed, no more frequently than every 15\nminutes.  Network, AsyncStorage etc can be used (anything except UI), so\nperfect for things like a background data sync for offline support.\n\nBehind the scenes, this library takes a different approach with each platform:\n\n- **Android**: A native implementation, which provides scheduling on top of\n  RN's built-in [Headless JS](https://facebook.github.io/react-native/docs/headless-js-android.html)\n  (Android only).\n  - Min API level: 16 (Android 4.1).\n- **iOS**: A proxy around [react-native-background-fetch](https://github.com/transistorsoft/react-native-background-fetch),\n  which uses the iOS-specific `Background Fetch` technique.\n\nTo achieve a unified API, this library exposes the lowest common denominator\n(e.g. only support for a single task, even though Android can support multiple).\n\nFor more per-platform flexibility, there are other platform-specific libraries\nwith more granular customisation.\n\n## Installation\n\n```bash\n$ npm install react-native-background-task --save\n```\n  \n### Android\n\n1. The linking of the library can be done automatically by running:\n\n  ```bash\n  $ react-native link react-native-background-task\n  ```\n\n2. One manual step is still needed - in your project file\n  `android/app/src/main/java/myapp/MainApplication.java`, add the following to\n  the end of the `onCreate()` method:\n  \n  ```java\n  BackgroundTaskPackage.useContext(this);\n  ```\n\n### iOS\n\nFor iOS support, this library relies on version 2.0.x of\n[react-native-background-fetch](https://github.com/transistorsoft/react-native-background-fetch)\nwhich can be installed as follows:\n\n```bash\n$ npm install react-native-background-fetch@2.0.x --save\n$ react-native link react-native-background-fetch\n```\n  \nThis library will behave correctly on iOS as long as `react-native-background-fetch`\nis installed alongside it, and has been linked with your project.\n\n## API\n\n### `define(task)`\n\nDefine the JS code that this module should be executing.\n\n- Should be called at the top level of your JS, **not** inside a component.\n  This is because in headless mode no components are mounted, but the code\n  still needs to be accessible.\n- Will overwrite any previously defined task.\n\nParameters:\n\n- **`task`**: **required** `() =\u003e void` - Function to be executed in the background\n\n### `schedule(options)`\n\nSpecify the scheduling options for the task, and register it with the\nplatform's scheduler.\n\n- Should be called from inside a component (e.g. your App's\n  `componentDidMount`).  This is to avoid double-scheduling when the task\n  launches in headless mode.\n- Will `console.warn` if the device is task was unable to be scheduled.\n\nParameters:\n\n- **`options?`**: `Object` - Any configuration you want to be set with\n  the task.  Note that most of these will only work on one platform.\n  \n  - **`period?`**: `number` - (Android only) Desired number of seconds between each\n    execution of the task.  Even on Android, the OS will only take this as a\n    recommendation, and will enforce a minimum of 15 minutes (similar to iOS).\n    Default is 900 (15 minutes)\n  - **`timeout?`**: `number` - (Android only) Number of seconds the task will have\n    to execute.  iOS has a hardcoded limit of 30 seconds.  Default 30 seconds.\n\n### `finish()`\n\n**Must be called at the end of your task** to indicate to the OS that it's\nfinished.  (Only required on iOS, no-op on Android).\n\n### `cancel()`\n\nCancels any currently scheduled task.\n\n### `statusAsync()`\n\nQuery the status of background tasks within this app.  Returns a Promise with\nan object of the following shape:\n\n- **`available`**: `boolean` - Whether background tasks are available to the app.\n  On Android this will always be true, but on iOS background tasks could be\n  blocked (see [UIBackgroundRefreshStatus](https://developer.apple.com/documentation/uikit/uibackgroundrefreshstatus)).\n- **`unavailableReason?`**: `string` - If unavailable, gives the reason:\n    - **`BackgroundTask.UNAVAILABLE_DENIED`**: - The user explicitly disabled\n      background behavior for this app or for the whole system.\n    - **`BackgroundTask.UNAVAILABLE_RESTRICTED`**: - Background updates\n      unavailable and can't be enabled by the user (e.g. parental controls).\n\n## Limitations\n\n- Tasks cannot be scheduled any more frequently than every 15 minutes.\n- The exact timings of task execution are unpredictable, as both Anrdoid and\n  iOS use black-box algorithms, which depend on factors like device sleep\n  state.  This library should only be used for tasks that are an incremental \n  feature, and can have inexact timing, such as the periodic background syncing\n  of data.  You should be prepared for the case that background task doesn't\n  fires at all.\n  \nAndroid:\n\n- Tasks will not run while the app is in the foreground, and scheduling can be\n  made even more imprecise when the app goes in/out of the foreground (as tasks\n  are rescheduled as soon as the app goes into the background).\n  \niOS:\n\n- iOS Background Fetch will not continue to run after a user manually closes\n  the app.  (The app being closed by the OS to free up memory etc. should be\n  fine).\n- Background tasks will not be scheduled in the simulator.  You'll need to\n  either test it on a real device, or use the\n  [Simulate Background Fetch](https://developer.apple.com/library/content/documentation/IDEs/Conceptual/iOS_Simulator_Guide/TestingontheiOSSimulator/TestingontheiOSSimulator.html#//apple_ref/doc/uid/TP40012848-CH4-SW5)\n  feature of Xcode.\n- The user can disable Background App Refresh for your app from their Settings\n  (use `statusAsync()` to check for this).\n\n\n## Debugging\n\n### Android\n\n```bash\n$ adb logcat *:S ReactNative:V ReactNativeJS:V BackgroundTask:V\n```\n\nKeep in mind that after the app leaves the foreground, you'll have to wait at\nleast 50% of the desired period (so, default is 7m30s) before the task\nexecutes.\n\n## Examples\n\nA full example project can be found here:\nhttps://github.com/jamesisaac/RNBackgroundTaskExample\n\n### Simple\n\n```js\nimport React from 'react'\nimport { Text } from 'react-native'\nimport BackgroundTask from 'react-native-background-task'\n\nBackgroundTask.define(() =\u003e {\n  console.log('Hello from a background task')\n  BackgroundTask.finish()\n})\n\nclass MyApp extends React.Component {\n  componentDidMount() {\n    BackgroundTask.schedule()\n  }\n  \n  render() {\n    return \u003cText\u003eHello world\u003c/Text\u003e\n  }\n}\n```\n\n### Fetch / store data\n\n```js\nimport React from 'react'\nimport { Alert, AsyncStorage, Button } from 'react-native'\nimport BackgroundTask from 'react-native-background-task'\n\nBackgroundTask.define(async () =\u003e {\n  // Fetch some data over the network which we want the user to have an up-to-\n  // date copy of, even if they have no network when using the app\n  const response = await fetch('http://feeds.bbci.co.uk/news/rss.xml')\n  const text = await response.text()\n  \n  // Data persisted to AsyncStorage can later be accessed by the foreground app\n  await AsyncStorage.setItem('@MyApp:key', text)\n  \n  // Remember to call finish()\n  BackgroundTask.finish()\n})\n\nclass MyApp extends React.Component {\n  componentDidMount() {\n    BackgroundTask.schedule({\n      period: 1800, // Aim to run every 30 mins - more conservative on battery\n    })\n    \n    // Optional: Check if the device is blocking background tasks or not\n    this.checkStatus()\n  }\n  \n  async checkStatus() {\n    const status = await BackgroundTask.statusAsync()\n    \n    if (status.available) {\n      // Everything's fine\n      return\n    }\n    \n    const reason = status.unavailableReason\n    if (reason === BackgroundTask.UNAVAILABLE_DENIED) {\n      Alert.alert('Denied', 'Please enable background \"Background App Refresh\" for this app')\n    } else if (reason === BackgroundTask.UNAVAILABLE_RESTRICTED) {\n      Alert.alert('Restricted', 'Background tasks are restricted on your device')\n    }\n  }\n  \n  render() {\n    return (\n      \u003cView\u003e\n        \u003cButton\n          title=\"Read results from AsyncStorage\"\n          onPress={async () =\u003e {\n            const result = await AsyncStorage.getItem('@MyApp:key')\n            console.log(result) \n          }}\n        /\u003e\n      \u003c/View\u003e\n    )\n  }\n}\n```","funding_links":[],"categories":["Java"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjamesisaac%2Freact-native-background-task","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjamesisaac%2Freact-native-background-task","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjamesisaac%2Freact-native-background-task/lists"}