简体   繁体   中英

How to schedule background job at specific time in react native

I want to execute some Task T at specific time in a day in background in react native. I see that it is possible in android as of now using Headless JS . I found that this library implemented this https://github.com/vikeri/react-native-background-job and allows you to execute stuff in background.

This is not completely what I am looking, it doesn't allows you to schedule a task T at specific time. Does anyone know any work around for this ?

I have checked this thread Execute code at specific time in react native where I didn't find a solution of my issue.

I came across a similar issue, unfortunately, you can't specify something similar to CRON action in RN.

My solution to that problem is to use this library https://github.com/ocetnik/react-native-background-timer and calculate the difference between current time and time that the task is scheduled for.

The calculated time should be in ms, so you can use it with provided function setTimeout :

// 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);

Example:

Let's say you want to schedule task for tomorrow at 16th, in componentDidMount you can calculate time between now and scheduled date. Let's use moment for that:

componentDidMount(){
  const scheduledDate = 
   moment().add(1,'d').set({hour:16,minute:0,second:0,millisecond:0})
  const diffTime = scheduledDate.diff(moment())
  this.timeoutId = BackgroundTimer.setTimeout(() => {
    console.log('tac');
  }, diffTime);
}

componentWillUnmount(){
 BackgroundTimer.clearTimeout(this.timeoutId);
}

Note that this solution is vulnerable to a user changing the time on his phone. The perfect solution would be to use some external service to fetch time.

Second note, the app needs to be at least in the background for this to work.

JavaScript code runs in foreground with only one thread. If you need scheduled background task, you need to implement native modules, as described in RN document:

https://facebook.github.io/react-native/docs/native-modules-ios.html

https://facebook.github.io/react-native/docs/native-modules-android.html

Of course, all the platform restrictions (especially iOS) apply.

Create class and add this in your class

public static final long NOTIFY_INTERVAL = 10 * 1000; // 30 minutes

@Override
    public void onCreate() {
        // cancel if already existed
        if (mTimer != null) {
            mTimer.cancel();
        } else {
            // recreate new
            mTimer = new Timer();
        }
        // schedule task
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
    }

class TimeDisplayTimerTask extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // code
                }
            });
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM