Skip to content

Commit

Permalink
removed queue to prevent multiple executions of the task
Browse files Browse the repository at this point in the history
  • Loading branch information
xRahul committed May 5, 2018
1 parent bd7cac0 commit 13e0ca3
Show file tree
Hide file tree
Showing 34 changed files with 157 additions and 105 deletions.
71 changes: 25 additions & 46 deletions App.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
} from 'react-native'

import BackgroundTask from 'react-native-background-task'
import queueFactory from 'react-native-queue'
import PushNotification from 'react-native-push-notification'


Expand All @@ -35,6 +34,12 @@ PushNotification.configure({
})

const checkUrlForText = async (url, searchText) => {

if (!url || !searchText) {
BackgroundTask.cancel()
return
}

if (url.substring(0, 4) != "http") {
url = 'https://'+url
}
Expand All @@ -53,28 +58,10 @@ const checkUrlForText = async (url, searchText) => {

BackgroundTask.define(async () => {

// Init queue
queue = await queueFactory();

// Register job worker
queue.addWorker('background-check-url-for-search-text', async (id, payload) => {

checkUrlForText(payload.url, payload.searchText)

queue.createJob(
'background-check-url-for-search-text',
{ url: payload.url, searchText: payload.searchText }, // Supply the image url we want prefetched in this job to the payload.
{ attempts: 5, timeout: 23000 }, // Retry job on failure up to 5 times. Timeout job in 15 sec (prefetch is probably hanging if it takes that long).
false // Must pass false as the last param so the queue starts up in the background task instead of immediately.
);
});
const urlBackgroundTask = await AsyncStorage.getItem('url')
const searchTextBackgroundTask = await AsyncStorage.getItem('searchText')

// Start the queue with a lifespan
// IMPORTANT: OS background tasks are limited to 30 seconds or less.
// NOTE: Queue lifespan logic will attempt to stop queue processing 500ms less than passed lifespan for a healthy shutdown buffer.
// IMPORTANT: Queue processing started with a lifespan will ONLY process jobs that have a defined timeout set.
// Additionally, lifespan processing will only process next job if job.timeout < (remainingLifespan - 500).
await queue.start(25000); // Run queue for at most 25 seconds.
await checkUrlForText(urlBackgroundTask, searchTextBackgroundTask)

// finish() must be called before OS hits timeout.
BackgroundTask.finish();
Expand All @@ -90,38 +77,38 @@ export default class App extends Component<{}> {
url: '',
searchText: '',
taskSet: 'no',
queue: null,
loading: false
};

queueFactory()
.then(queue => {
this.setState({queue});
})

this.initAsyncStorage()
}

initAsyncStorage() {
AsyncStorage.getItem('url').then((value) => {if (value) this.persistState('url', value)}).catch((error) => console.log(error))
AsyncStorage.getItem('searchText').then((value) => {if (value) this.persistState('searchText', value)}).catch((error) => console.log(error))
AsyncStorage.getItem('taskSet').then((value) => {if (value) this.persistState('taskSet', value)}).catch((error) => console.log(error))
// AsyncStorage.getItem('queue').then((value) => {if (value) this.persistState('queue', value)}).catch((error) => console.log(error))
// AsyncStorage.getItem('loading').then((value) => {if (value) this.persistState('loading', value)}).catch((error) => console.log(error))
}

componentDidMount() {
// Optional: Check if the device is blocking background tasks or not
this.checkStatus()
BackgroundTask.schedule(); // Schedule the task to run every ~15 min if app is closed.

if (this.state.taskSet == 'yes') {
// Schedule the task to run every ~15 min if app is closed.
BackgroundTask.cancel()
BackgroundTask.schedule()
} else {
BackgroundTask.cancel()
}
}

async persistState(key, value) {
persistState(key, value) {
var obj = {}
obj[key] = value
this.setState(obj)
if (typeof value != 'boolean') {
await AsyncStorage.setItem(key, value)
AsyncStorage.setItem(key, value)
}
}

Expand All @@ -142,22 +129,16 @@ export default class App extends Component<{}> {
}
}

createPrefetchJobs() {
async createPrefetchJobs() {
this.persistState('loading', true)
this.persistState('url', this.state.url.trim())
this.persistState('taskSet', 'yes')

// Create the prefetch job for the first <Image> component.
this.state.queue.createJob(
'background-check-url-for-search-text',
{ url: this.state.url, searchText: this.state.searchText }, // Supply the image url we want prefetched in this job to the payload.
{ attempts: 5, timeout: 23000 }, // Retry job on failure up to 5 times. Timeout job in 15 sec (prefetch is probably hanging if it takes that long).
false // Must pass false as the last param so the queue starts up in the background task instead of immediately.
);
BackgroundTask.cancel()
BackgroundTask.schedule()

this.persistState('taskSet', 'yes')
await checkUrlForText(this.state.url, this.state.searchText)
this.persistState('loading', false)

checkUrlForText(this.state.url, this.state.searchText)
}

deletePrefetchJobs() {
Expand Down Expand Up @@ -191,14 +172,12 @@ export default class App extends Component<{}> {
{this.state.taskSet == 'no' && <Button
title={"Start Checking"}
onPress={ this.createPrefetchJobs.bind(this) }
disabled={!this.state.queue}
/> }
{this.state.taskSet == 'yes' && <Button
title={"Stop Checking"}
onPress={ this.deletePrefetchJobs.bind(this) }
disabled={!this.state.queue}
/> }
{!this.state.queue || this.state.loading && <ActivityIndicator size="large" color="#7a42f4" /> }
{this.state.loading && <ActivityIndicator size="large" color="#7a42f4" /> }
</ScrollView>
);
}
Expand Down
Binary file modified android/.gradle/2.14.1/taskArtifacts/cache.properties.lock
Binary file not shown.
Binary file modified android/.gradle/2.14.1/taskArtifacts/fileHashes.bin
Binary file not shown.
Binary file modified android/.gradle/2.14.1/taskArtifacts/fileSnapshots.bin
Binary file not shown.
Binary file not shown.
Binary file modified android/.gradle/2.14.1/taskArtifacts/taskArtifacts.bin
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
5 changes: 3 additions & 2 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ apply from: "../../node_modules/react-native/react.gradle"
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
def enableSeparateBuildPerCPUArchitecture = true

/**
* Run Proguard to shrink the Java bytecode in release builds.
Expand Down Expand Up @@ -121,7 +121,7 @@ android {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
universalApk true // If true, also generate a universal APK
include "armeabi-v7a", "x86"
}
}
Expand All @@ -148,6 +148,7 @@ android {
}

dependencies {
compile project(':react-native-background-fetch')
compile project(':react-native-push-notification')
compile project(':react-native-background-task')
compile project(':realm')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import android.app.Application;

import com.facebook.react.ReactApplication;
import com.transistorsoft.rnbackgroundfetch.RNBackgroundFetchPackage;
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;
import com.jamesisaac.rnbackgroundtask.BackgroundTaskPackage;
import io.realm.react.RealmReactPackage;
Expand All @@ -26,6 +27,7 @@ public boolean getUseDeveloperSupport() {
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNBackgroundFetchPackage(),
new ReactNativePushNotificationPackage(),
new BackgroundTaskPackage(),
new RealmReactPackage()
Expand Down
7 changes: 7 additions & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,12 @@ allprojects {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
// For latest Google Apis
maven {
url 'https://maven.google.com'
}
maven {
url "$rootDir/../node_modules/react-native-background-fetch/android/libs"
}
}
}
2 changes: 2 additions & 0 deletions android/settings.gradle
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
rootProject.name = 'NotifyAvailability'
include ':react-native-background-fetch'
project(':react-native-background-fetch').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-background-fetch/android')
include ':react-native-push-notification'
project(':react-native-push-notification').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-push-notification/android')
include ':react-native-background-task'
Expand Down
Loading

0 comments on commit 13e0ca3

Please sign in to comment.