{"id":13777176,"url":"https://github.com/vikeri/react-native-background-job","last_synced_at":"2025-05-11T11:32:53.281Z","repository":{"id":14458075,"uuid":"76574111","full_name":"vikeri/react-native-background-job","owner":"vikeri","description":"Schedule background jobs in React Native that run your JavaScript when your app is in the background/killed.","archived":false,"fork":false,"pushed_at":"2023-11-06T19:34:12.000Z","size":1093,"stargazers_count":744,"open_issues_count":102,"forks_count":108,"subscribers_count":17,"default_branch":"master","last_synced_at":"2024-04-14T11:58:55.185Z","etag":null,"topics":["background-jobs","react-native","scheduled-jobs"],"latest_commit_sha":null,"homepage":null,"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/vikeri.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":"2016-12-15T15:59:10.000Z","updated_at":"2024-04-10T09:03:29.000Z","dependencies_parsed_at":"2024-01-06T22:30:00.042Z","dependency_job_id":"68e0a377-d042-42d9-9ff3-5c2fedc8c147","html_url":"https://github.com/vikeri/react-native-background-job","commit_stats":{"total_commits":150,"total_committers":16,"mean_commits":9.375,"dds":0.3866666666666667,"last_synced_commit":"83cde8515a2d8e3af8fa0475f6fd233386a3af2d"},"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vikeri%2Freact-native-background-job","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vikeri%2Freact-native-background-job/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vikeri%2Freact-native-background-job/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vikeri%2Freact-native-background-job/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vikeri","download_url":"https://codeload.github.com/vikeri/react-native-background-job/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225043063,"owners_count":17411924,"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":["background-jobs","react-native","scheduled-jobs"],"created_at":"2024-08-03T18:00:38.945Z","updated_at":"2024-11-17T13:30:32.257Z","avatar_url":"https://github.com/vikeri.png","language":"Java","funding_links":[],"categories":["\u003ca name=\"OS-\u0026-System-\u0026-File-Manager:-Native-Modules\"\u003eOS, System \u0026 File Manager: Native Modules\u003c/a\u003e","Index"],"sub_categories":["Async and Middleware"],"readme":"# react-native-background-job [![npm version](https://badge.fury.io/js/react-native-background-job.svg)](https://badge.fury.io/js/react-native-background-job) [![CircleCI](https://circleci.com/gh/vikeri/react-native-background-job.svg?style=svg)](https://circleci.com/gh/vikeri/react-native-background-job)\n\nSchedule background jobs that run your JavaScript when your app is in the background or if you feel brave even in foreground.\n\nThe jobs will run even if the app has been closed and, by default, also persists over restarts.\n\nThis library relies on React Native's [`HeadlessJS`](https://facebook.github.io/react-native/docs/headless-js-android.html) which is currently only supported on Android.\n\nOn the native side it uses either [`Firebase JobDispatcher`](https://github.com/firebase/firebase-jobdispatcher-android) or a [`AlarmManager`](https://developer.android.com/reference/android/app/AlarmManager.html).\n\n-   Firebase JobDispatcher (default): The jobs can't be scheduled exactly and depending on the Android API version different `period` time is allowed. `FirebaseJobDispatcher` is the most battery efficient backward compatible way of scheduling background tasks. \n\n-   AlarmManager by setting `exact` to `true`: Simple propriatery implementation that is only ment to be used while testing. It only cares about executing on time, all other parameters are ignored - job is not persisted on reboot.\n\n## Requirements\n\n-   RN 0.36+\n-   Android API 16+\n\n## Supported platforms\n\n-   Android\n\nWant iOS? Go in and vote for Headless JS to be implemented for iOS: [Product pains](https://productpains.com/post/react-native/headless-js-for-ios)\n\n## Getting started\n\n`$ yarn add react-native-background-job`\n\nor\n\n`$ npm install react-native-background-job --save`\n\n### Mostly automatic installation\n\n`$ react-native link react-native-background-job`\n\n### Manual installation\n\n\u003c!--\n#### iOS\n\n1. In XCode, in the project navigator, right click `Libraries` ➜ `Add Files to [your project's name]`\n2. Go to `node_modules` ➜ `react-native-background-job` and add `RNBackgroundJob.xcodeproj`\n3. In XCode, in the project navigator, select your project. Add `libRNBackgroundJob.a` to your project's `Build Phases` ➜ `Link Binary With Libraries`\n4. Run your project (`Cmd+R`)\u003c\n\n--\u003e\n\n#### Android\n\n1.  Open up `android/app/src/main/java/[...]/MainApplication.java`\n\n    -   Add `import com.pilloxa.backgroundjob.BackgroundJobPackage;` to the imports at the top of the file.\n    -   Add `new BackgroundJobPackage()` to the list returned by the `getPackages()` method.\n\n2.  Append the following lines to `android/settings.gradle`:\n\n        include ':react-native-background-job'\n        project(':react-native-background-job').projectDir = new File(rootProject.projectDir, \t'../node_modules/react-native-background-job/android')\n\n3.  Insert the following lines inside the dependencies block in `android/app/build.gradle` and bump the minSdkVersion to 21:\n\n        compile project(':react-native-background-job')\n\n## Usage\n\nThe jobs have to be registered each time React Native starts, this is done using the `register` function. Since HeadlessJS does not mount any components the `register` function must be run outside of any class definitions (see [example/index.android.js](example/index.android.js#L24-L35))\n\nRegistering the job does not mean that the job is scheduled, it just informs React Native that this `job` function should be tied to this `jobKey`. The job is then scheduled using the `schedule` function. **By default, the job will not fire while the app is in the foreground**. This is since the job is run on the only JavaScript thread and if running the job when app is in the foreground it would freeze the app. By setting `allowExecutionInForeground` to `true` you allow this behavior. It is recommended that you do't use this, but for quick jobs should be fine.\n\nFor a full example check out [example/index.android.js](example/index.android.js)\n\n## API\n\n\u003c!-- Generated by documentation.js. Update this documentation by updating the source code. --\u003e\n\n#### Table of Contents\n\n-   [register](#register)\n    -   [Parameters](#parameters)\n    -   [Examples](#examples)\n-   [schedule](#schedule)\n    -   [Parameters](#parameters-1)\n    -   [Examples](#examples-1)\n-   [cancel](#cancel)\n    -   [Parameters](#parameters-2)\n    -   [Examples](#examples-2)\n-   [cancelAll](#cancelall)\n    -   [Examples](#examples-3)\n-   [setGlobalWarnings](#setglobalwarnings)\n    -   [Parameters](#parameters-3)\n    -   [Examples](#examples-4)\n-   [isAppIgnoringBatteryOptimization](#isappignoringbatteryoptimization)\n    -   [Parameters](#parameters-4)\n    -   [Examples](#examples-5)\n\n### register\n\n[index.js:39-55](https://github.com/vikeri/react-native-background-job/blob/ff0fe73675342c38e391093f64d9e25dafe6d4f2/index.js#L39-L55 \"Source code on GitHub\")\n\nRegisters the job and the functions they should run.\n\nThis has to run on each initialization of React Native and it has to run in the global scope and not inside any\ncomponent life cycle methods. See example project. Only registering the job will not schedule the job.\nIt has to be scheduled by `schedule` to start running.\n\n#### Parameters\n\n-   `obj` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** \n    -   `obj.jobKey` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** A unique key for the job\n    -   `obj.job` **[function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** The JS-function that will be run\n\n#### Examples\n\n```javascript\nimport BackgroundJob from 'react-native-background-job';\n\nconst backgroundJob = {\n jobKey: \"myJob\",\n job: () =\u003e console.log(\"Running in background\")\n};\n\nBackgroundJob.register(backgroundJob);\n```\n\n### schedule\n\n[index.js:95-142](https://github.com/vikeri/react-native-background-job/blob/ff0fe73675342c38e391093f64d9e25dafe6d4f2/index.js#L95-L142 \"Source code on GitHub\")\n\nSchedules a new job.\n\nThis only has to be run once while `register` has to be run on each initialization of React Native.\n\n#### Parameters\n\n-   `obj` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** \n    -   `obj.jobKey` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** A unique key for the job that was used for registering, and be used for canceling in later stage.\n    -   `obj.timeout` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** The amount of time (in ms) after which the React instance should be terminated regardless of whether the task has completed or not. (optional, default `2000`)\n    -   `obj.period` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** The frequency to run the job with (in ms). This number is not exact, Android may modify it to save batteries. Note: For Android \u003e N, the minimum is 900 0000 (15 min). (optional, default `900000`)\n    -   `obj.persist` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** If the job should persist over a device restart. (optional, default `true`)\n    -   `obj.override` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Whether this Job should replace pre-existing jobs with the same key. (optional, default `true`)\n    -   `obj.networkType` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** Only run for specific network requirements. (optional, default `NETWORK_TYPE_NONE`)\n    -   `obj.requiresCharging` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Only run job when device is charging, (not respected by pre Android N devices) [docs](https://developer.android.com/reference/android/app/job/JobInfo.Builder.html#setRequiresCharging(boolean)) (optional, default `false`)\n    -   `obj.requiresDeviceIdle` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Only run job when the device is idle, (not respected by pre Android N devices) [docs](https://developer.android.com/reference/android/app/job/JobInfo.Builder.html#setRequiresDeviceIdle(boolean)) (optional, default `false`)\n    -   `obj.exact` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Schedule an job to be triggered precisely at the provided period. Note that this is not power-efficient way of doing things. (optional, default `false`)\n    -   `obj.allowWhileIdle` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Allow the scheduled job to execute also while it is in doze mode. (optional, default `false`)\n    -   `obj.allowExecutionInForeground` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Allow the scheduled job to be executed even when the app is in foreground. Use it only for short running jobs. (optional, default `false`)\n    -   `obj.notificationText` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** For Android SDK \u003e 26, what should the notification text be (optional, default `\"Running in background...\"`)\n    -   `obj.notificationTitle` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** For Android SDK \u003e 26, what should the notification title be (optional, default `\"Background job\"`)\n\n#### Examples\n\n```javascript\nimport BackgroundJob from 'react-native-background-job';\n\nconst backgroundJob = {\n jobKey: \"myJob\",\n job: () =\u003e console.log(\"Running in background\")\n};\n\nBackgroundJob.register(backgroundJob);\n\nvar backgroundSchedule = {\n jobKey: \"myJob\",\n}\n\nBackgroundJob.schedule(backgroundSchedule)\n  .then(() =\u003e console.log(\"Success\"))\n  .catch(err =\u003e console.err(err));\n```\n\n### cancel\n\n[index.js:156-166](https://github.com/vikeri/react-native-background-job/blob/ff0fe73675342c38e391093f64d9e25dafe6d4f2/index.js#L156-L166 \"Source code on GitHub\")\n\nCancel a specific job\n\n#### Parameters\n\n-   `obj` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** \n    -   `obj.jobKey` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The unique key for the job\n\n#### Examples\n\n```javascript\nimport BackgroundJob from 'react-native-background-job';\n\nBackgroundJob.cancel({jobKey: 'myJob'})\n  .then(() =\u003e console.log(\"Success\"))\n  .catch(err =\u003e console.err(err));\n```\n\n### cancelAll\n\n[index.js:177-187](https://github.com/vikeri/react-native-background-job/blob/ff0fe73675342c38e391093f64d9e25dafe6d4f2/index.js#L177-L187 \"Source code on GitHub\")\n\nCancels all the scheduled jobs\n\n#### Examples\n\n```javascript\nimport BackgroundJob from 'react-native-background-job';\n\nBackgroundJob.cancelAll()\n  .then(() =\u003e console.log(\"Success\"))\n  .catch(err =\u003e console.err(err));\n```\n\n### setGlobalWarnings\n\n[index.js:199-201](https://github.com/vikeri/react-native-background-job/blob/ff0fe73675342c38e391093f64d9e25dafe6d4f2/index.js#L199-L201 \"Source code on GitHub\")\n\nSets the global warning level\n\n#### Parameters\n\n-   `warn` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** \n\n#### Examples\n\n```javascript\nimport BackgroundJob from 'react-native-background-job';\n\nBackgroundJob.setGlobalWarnings(false);\n```\n\n### isAppIgnoringBatteryOptimization\n\n[index.js:213-229](https://github.com/vikeri/react-native-background-job/blob/ff0fe73675342c38e391093f64d9e25dafe6d4f2/index.js#L213-L229 \"Source code on GitHub\")\n\nChecks Whether app is optimising battery using Doze,returns Boolean.\n\n#### Parameters\n\n-   `callback` **Callback** gets called with according parameters after result is received from Android module.\n\n#### Examples\n\n```javascript\nimport BackgroundJob from 'react-native-background-job';\n\nBackgroundJob.isAppIgnoringBatteryOptimization((err, isIgnoring) =\u003e console.log(`Callback: isIgnoring = ${isIgnoring}`))\n  .then(isIgnoring =\u003e console.log(`Promise: isIgnoring = ${isIgnoring}`))\n  .catch(err =\u003e console.err(err));\n```\n\n## Troubleshooting\n\n### `No task registered for key myJob`\n\nMake sure you call the `register` function at the global scope (i.e. not in any component life cycle methods (render, iDidMount etc)). Since the components are not rendered in Headless mode if you run the register function there it will not run in the background and hence the library will not find which function to run.\n\nSee [example project](https://github.com/vikeri/react-native-background-job/blob/c0e4bc8e9dd692695169d6c9855d39e2ff917a61/example/index.android.js#L20-L25)\n\n### `AppState.currentState` is `\"active\"` when I'm running my Headless task in the background\n\nThis is a [React Native issue](https://github.com/facebook/react-native/issues/11561), you can get around it by calling `NativeModules.AppState.getCurrentAppState` directly instead.\n\n### My job always runs in the background even if I specified `requiresCharging`, `requiresDeviceIdle` or a specific `networkType`\n\nThis is an [Android issue](https://code.google.com/p/android/issues/detail?id=81265), it seems that you can not have these restrictions at the same time as you have a periodic interval for pre Android N devices.\n\n## Pull Request Details\n\n### Included function for checking if the app is ignoring battery optimizations. #62\n\nIn Android SDK versions greater than 23, Doze is being used by apps by default, in order to optimize battery by temporarily turning off background tasks when the phone is left undisturbed for some hours.\n\nBut, some apps may require background tasks to keep running, ignoring doze and not optimizing battery (this means battery needs to be traded off for performance as per required). Apps that require continuous syncing of data to the server at short intervals of time are examples of such apps.\n\nIt would be good if the developer can check whether the app is optimizing battery. If it is, the user can be notified that the app would not perform as per expected and it will work properly only if the user manually removes it from the battery optimizing apps list which can be found in\nSettings-\u003e Battery -\u003e Options (button on top right) -\u003e Battery Optimization and then selecting \"All Apps\" to change the battery optimization settings for the particular app.\n\nThe Changes that have been made are specifically for that purpose, a function  (isAppIgnoringBatteryOptimization) has been included. It checks if the app is ignoring battery optimization and returns false if it is optimizing battery (in which case the user has to manually remove it from battery settings) and true otherwise.\n\nLogic has also been added for scheduling the task by ignoring battery optimizations, if the app has been manually removed from the battery optimization list in settings (by the User).\n\n## Sponsored by\n\n[![pilloxa](http://pilloxa.com/images/pilloxa-round-logo.svg)](http://pilloxa.com)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvikeri%2Freact-native-background-job","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvikeri%2Freact-native-background-job","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvikeri%2Freact-native-background-job/lists"}