Vue NativeVue Native
Guide
Components
Composables
Navigation
  • iOS
  • Android
  • macOS
GitHub
Guide
Components
Composables
Navigation
  • iOS
  • Android
  • macOS
GitHub
  • Device & System

    • useNetwork
    • useAppState
    • useColorScheme
    • useDeviceInfo
    • useDimensions
    • usePlatform
  • Storage & Files

    • useAsyncStorage
    • useSecureStorage
    • useFileSystem
    • useDatabase
  • Sensors & Hardware

    • useGeolocation
    • useBiometry
    • useHaptics
    • useSensors
    • useBluetooth
  • Media

    • useCamera
    • useAudio
    • useCalendar
    • useContacts
  • Networking

    • useHttp
    • useWebSocket
  • Permissions

    • usePermissions
  • Navigation

    • useBackHandler
    • useSharedElementTransition
  • UI

    • useKeyboard
    • useClipboard
    • useShare
    • useLinking
    • useAnimation
    • useGesture
    • useNotifications
    • useI18n
    • usePerformance
  • Authentication

    • useAppleSignIn
    • useGoogleSignIn
  • Monetization & Updates

    • useIAP
    • useOTAUpdate
    • useBackgroundTask
  • Desktop (macOS)

    • useWindow
    • useMenu
    • useFileDialog
    • useDragDrop

useBackgroundTask

Schedule and manage background tasks that run even when your app is not in the foreground. Uses BGTaskScheduler on iOS and WorkManager on Android.

Usage

<script setup>
import { useBackgroundTask } from '@thelacanians/vue-native-runtime'

const {
  scheduleTask, cancelTask, cancelAllTasks,
  completeTask, registerTask, onTaskExecute,
} = useBackgroundTask()

// Handle background task execution
onTaskExecute((taskId) => {
  console.log('Background task executing:', taskId)
  // Do your work, then signal completion
  syncData().then(() => completeTask(taskId))
})

// Schedule a background refresh
async function scheduleSync() {
  await scheduleTask('com.myapp.sync', {
    type: 'refresh',
    requiresNetworkConnectivity: true,
    earliestBeginDate: Date.now() + 15 * 60 * 1000, // 15 min from now
  })
}
</script>

Setup

iOS

Register your task identifiers in Info.plist:

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
  <string>com.myapp.sync</string>
  <string>com.myapp.cleanup</string>
</array>

Enable the "Background processing" and/or "Background fetch" capabilities in Xcode.

Android

Add WorkManager to your build.gradle dependencies (already included in VueNativeCore):

implementation "androidx.work:work-runtime-ktx:2.9.0"

No additional manifest entries are required; WorkManager handles them automatically.

API

useBackgroundTask(): {
  registerTask: (taskId: string) => Promise<void>
  scheduleTask: (taskId: string, options?: BackgroundTaskOptions) => Promise<void>
  cancelTask: (taskId: string) => Promise<void>
  cancelAllTasks: () => Promise<void>
  completeTask: (taskId: string, success?: boolean) => Promise<void>
  onTaskExecute: (handler: (taskId: string) => void, taskId?: string) => () => void
}

Methods

registerTask(taskId)

Register a task identifier with the OS. On iOS, this sets up the BGTaskScheduler handler. On Android, this is a no-op (registration happens automatically at schedule time).

ParameterTypeDescription
taskIdstringThe task identifier (e.g., 'com.myapp.sync'). Must match Info.plist on iOS.

scheduleTask(taskId, options?)

Schedule a background task for future execution.

ParameterTypeDescription
taskIdstringThe task identifier.
optionsBackgroundTaskOptions?Scheduling options.

BackgroundTaskOptions:

PropertyTypeDefaultDescription
type'refresh' | 'processing''refresh'Task type. 'refresh' for short tasks (~30s), 'processing' for long-running tasks.
earliestBeginDatenumber?-Earliest time the task can begin (Unix timestamp in ms).
requiresNetworkConnectivityboolean?falseWhether the task needs network access.
requiresExternalPowerboolean?falseWhether the device must be charging.
intervalnumber?15Interval in minutes for periodic tasks (Android only, requires type: 'processing').

cancelTask(taskId)

Cancel a scheduled task.

ParameterTypeDescription
taskIdstringThe task identifier to cancel.

cancelAllTasks()

Cancel all scheduled background tasks.

completeTask(taskId, success?)

Signal that a background task has finished. Must be called on iOS when onTaskExecute fires, or the system will throttle future tasks.

ParameterTypeDefaultDescription
taskIdstring-The task identifier.
successboolean?trueWhether the task completed successfully.

onTaskExecute(handler, taskId?)

Register a callback for when a background task executes. Returns an unsubscribe function.

ParameterTypeDescription
handler(taskId: string) => voidCalled when a task fires.
taskIdstring?If provided, only fires for this specific task. Otherwise acts as a catch-all.

Platform Differences

FeatureiOSAndroid
Short refresh tasksBGAppRefreshTaskRequest (~30s)OneTimeWorkRequest
Long processing tasksBGProcessingTaskRequest (minutes)PeriodicWorkRequest
RegistrationMust list in Info.plistAutomatic
completeTask()Required (system enforced)No-op (Worker handles completion)
Periodic tasksNot supported (reschedule manually)Built-in via interval option
Minimum intervalSystem-determined15 minutes (WorkManager minimum)

Example

<script setup>
import { onMounted } from '@thelacanians/vue-native-runtime'
import { useBackgroundTask } from '@thelacanians/vue-native-runtime'

const { scheduleTask, cancelTask, completeTask, onTaskExecute } = useBackgroundTask()

onTaskExecute(async (taskId) => {
  try {
    // Perform sync work
    const response = await fetch('https://api.myapp.com/sync')
    const data = await response.json()
    await saveData(data)
    await completeTask(taskId, true)
  } catch (error) {
    await completeTask(taskId, false)
  }
}, 'com.myapp.datasync')

onMounted(async () => {
  await scheduleTask('com.myapp.datasync', {
    type: 'refresh',
    requiresNetworkConnectivity: true,
    earliestBeginDate: Date.now() + 60 * 60 * 1000, // 1 hour from now
  })
})
</script>

<template>
  <VView :style="{ flex: 1, justifyContent: 'center', alignItems: 'center' }">
    <VText>Background sync is scheduled</VText>
    <VButton :onPress="() => cancelTask('com.myapp.datasync')">
      <VText>Cancel Sync</VText>
    </VButton>
  </VView>
</template>

Notes

  • Background task execution is controlled by the OS and may not run exactly at the scheduled time.
  • iOS aggressively throttles background tasks for apps with low usage. Tasks may be delayed significantly.
  • Always call completeTask() on iOS when your handler finishes. Failing to do so causes the system to terminate your task and reduces future scheduling priority.
  • On Android, the minimum interval for periodic tasks is 15 minutes (WorkManager limitation).
  • Background tasks should be designed to be idempotent — they may run more than once or not at all.
Edit this page
Last Updated: 2/28/26, 11:24 PM
Contributors: Abdul Hamid, Claude Opus 4.6
Prev
useOTAUpdate