Giter Club home page Giter Club logo

react-native-background-timer's Introduction

React Native Background Timer

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

Installation

  1. If you use Expo to create a project you'll just need to "eject".

    expo eject
  2. Install React Native Background Timer package.

    yarn add react-native-background-timer
    # or using npm
    npm install react-native-background-timer --save
  3. Link React Native Background Timer library. This step is not necessary when you use React Native >= 0.60 (and your app is not ejected from Expo).

    react-native link react-native-background-timer
  4. If you use CocoaPods or React Native >= 0.60 (and your app is not ejected from Expo) or your app is ejected from Expo, then before running your app on iOS, make sure you have CocoaPods installed and run:

    cd ios
    pod install

Link the library manually if you get errors:

  • Android: TypeError: Cannot read property 'setTimeout' of undefined or TypeError: null is not an object (evaluating 'RNBackgroundTimer.setTimeout')
  • iOS: Native module cannot be null
Android manual linking
  • android/settings.gradle

    + include ':react-native-background-timer'
    + project(':react-native-background-timer').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-background-timer/android')
  • android/app/build.gradle

    dependencies {
    +   implementation project(':react-native-background-timer')
    }
  • android/app/src/main/java/com/your-app/MainApplication.java

    + import com.ocetnik.timer.BackgroundTimerPackage;
    
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
    +   new BackgroundTimerPackage()
      );
    }
iOS manual linking
  • ios/Podfile

    + pod 'react-native-background-timer', :path => '../node_modules/react-native-background-timer'

Usage

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

Crossplatform

To use the same code both on Android and iOS use runBackgroundTimer() and stopBackgroundTimer(). There can be used only one background timer to keep code consistent.

BackgroundTimer.runBackgroundTimer(() => { 
//code that will be called every 3 seconds 
}, 
3000);
//rest of code will be performing for iOS on background too

BackgroundTimer.stopBackgroundTimer(); //after this call all code on background stop run.

iOS

After iOS update logic of background task little bit changed. So we can't use as it was. You have to use only start() and stop() without parameters. And all code that is performing will continue performing on background including all setTimeout() timers.

Example:

BackgroundTimer.start();
// Do whatever you want incuding setTimeout;
BackgroundTimer.stop();

If you call stop() on background no new tasks will be started! Don't call .start() twice, as it stop performing previous background task and starts new. If it will be called on backgound no tasks will run.

Android

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.

// 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 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 the background
  	console.log('tac');
}, 10000);

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

Obsolete

Obsolete usage which doesn't support multiple background timers.

import {
  DeviceEventEmitter,
  NativeAppEventEmitter,
  Platform,
} from 'react-native';

import BackgroundTimer from 'react-native-background-timer';
const EventEmitter = Platform.select({
  ios: () => NativeAppEventEmitter,
  android: () => DeviceEventEmitter,
})();
// start a global timer
BackgroundTimer.start(5000); // delay in milliseconds only for Android
// listen for event
EventEmitter.addListener('backgroundTimer', () => {
	// this will be executed once after 5 seconds
	console.log('toe');
});
// stop the timer
BackgroundTimer.stop();

react-native-background-timer's People

Contributors

bogdanhossu avatar dependabot-preview[bot] avatar dependabot[bot] avatar dpunosevac avatar hillkim avatar ijzerenhein avatar jinshin1013 avatar jlexyc avatar julienkode avatar kulyk avatar menardi avatar ocetnik avatar olivierfreyssinet-old avatar prayash avatar reyalpsirc avatar rohitshampur avatar saeedzhiany avatar saghul avatar shhzdmrz avatar st0ffern avatar stoneman1 avatar thethanghn avatar thijsdaniels avatar xiiyy avatar xl666666 avatar yupferris avatar

Forkers

xl666666

react-native-background-timer's Issues

worker线程遗留问题

使用worker开的新线程中不支持RNOHContext序列化传参,底层OS暂不支持,导致无法在新线程中发送事件,需提需求。不开线程的情况下,因setTimeout属于异步方法,定时器效果不受影响。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.